public class TextBoxNum : System.Windows.Forms.TextBox
{
public TextBoxNum()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
protected override void OnKeyPress(System.Windows.Forms.KeyPressEventArgs e)
{
if(e.KeyChar.ToString().Length==1)
{
switch(e.KeyChar)
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case (char)System.Windows.Forms.Keys.Back://可以扩展其他键值的有效性
e.Handled = false;
break;
default:
//其他键值都不允许
e.Handled = true;
break;
}
}
base.OnKeyPress (e);
}
protected override void OnImeModeChanged(EventArgs e)
{
//屏蔽输入法
this.ImeMode = System.Windows.Forms.ImeMode.Disable;
base.OnImeModeChanged (e);
}
}
本文介绍了一个自定义的 TextBox 控件,该控件仅允许用户输入数字字符,并通过覆盖 OnKeyPress 事件来实现这一功能。同时,还禁用了输入法以确保用户只能输入有效的数字字符。
4871

被折叠的 条评论
为什么被折叠?



