如何在C#中跳过在文本框中键入
本文关键字:文本 | 更新日期: 2023-09-27 18:20:52
我想从C#的TextBox组件扩展一个类,并覆盖一个"On[Event]"方法,以便检查在文本框中键入的输入,并跳过要在文本框内输入的一些键。我正在搜索类似的东西(以下代码不是解决方案!):
public class NumText : TextBox
{
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.KeyValue >= 48 && e.KeyValue <= 57)
base.OnKeyDown(e);
}
}
如果需要防止按下多个键,请不要覆盖事件,而是添加一个新的事件。
this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this_onKeyPress);
private void this_onKeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyValue >= 48 && e.KeyValue <= 57)
e.Handled = true;
}
使用KeyEventArgs.Handled属性。
MSDN文章引用:
true以绕过控件的默认处理;否则,为false还将事件传递给默认的控件处理程序。