C# 文本框只能输入数字和退格键
程序员文章站
2022-05-16 10:09:43
...
参考:https://www.cnblogs.com/dtdnh520/articles/538684.html
按键不是数字和退格键,则忽略该键按下并释放的事件
private void TextBox_KeyPress(object sender, KeyPressEventArgs e)
{
KeyIsNotNumberOrBackspace(e);
}
/// <summary>
/// 按键不是数字和退格键
/// </summary>
/// <param name="e"></param>
/// <returns></returns>
public static void KeyIsNotNumberOrBackspace(KeyPressEventArgs e)
{
bool keyIsNotNumberOrBackspace = e.KeyChar != '\b' && !Char.IsDigit(e.KeyChar);
if (keyIsNotNumberOrBackspace)
{
e.Handled = true;
}
}