I want to create a new class inherits from System.Windows.Forms.TextBox and assign keypress and keyup events to my control.
Something like this :
class CurrencyTextbox : TextBox
{
private void CurrencyTextbox_KeyPress(object sender, KeyPressEventArgs e)
{
char ch = e.KeyChar;
if (!Char.IsDigit(ch) && ch != 8 && ch != 13)
{
e.Handled = true;
}
}
private void CurrencyTextbox_KeyUp(object sender, KeyEventArgs e)
{
if (!string.IsNullOrEmpty(CurrencyTextbox.Text))
{
System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("en-US");
Int64 valueBefore = Int64.Parse(开发者_Python百科CurrencyTextbox.Text, System.Globalization.NumberStyles.AllowThousands);
CurrencyTextbox.Text = String.Format(culture, "{0:N0}", valueBefore);
CurrencyTextbox.Select(CurrencyTextbox.Text.Length, 0);
}
}
}
You should override the protected virtual void OnKeyUp(KeyEventArgs e)
.
Make sure to call base.OnKeyUp(e)
, or the event will not be raised.
You can also add a regular event handler by writing KeyUp += CurrencyTextbox_KeyUp
精彩评论