如何从文本框继承并覆盖按键和上键事件
本文关键字:事件 覆盖 文本 继承 | 更新日期: 2023-09-27 18:10:49
我想创建一个继承自System.Windows.Forms.TextBox的新类,并为我的控件分配keypress和keyup事件。
像这样:
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(CurrencyTextbox.Text, System.Globalization.NumberStyles.AllowThousands);
CurrencyTextbox.Text = String.Format(culture, "{0:N0}", valueBefore);
CurrencyTextbox.Select(CurrencyTextbox.Text.Length, 0);
}
}
}
您应该重写protected virtual void OnKeyUp(KeyEventArgs e)
。
请确保调用base.OnKeyUp(e)
,否则事件将不会引发。
您还可以通过写入KeyUp += CurrencyTextbox_KeyUp