如何使用 C# 中的 KeyDown 事件使 TextBox 仅接收数字键值?

How to make TextBox to receive only number key values using KeyDown Event in C#?

只要按下数字键,我表单中的这段代码就会更新 textBox1.Text 两次。

private void textBox1_KeyDown( object sender, KeyEventArgs e ) {
     //MessageBox.Show();
     if( char.IsNumber((char)e.KeyCode) ) {
           textBox1.Text += (char)e.KeyCode;
     }
}

如果可以,请解释为什么? 修改代码或为此提供更好的解决方案。

输入(在 textbox1 中):

54321

输出:

1234554321

你可以这样试试:

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
   e.SuppressKeyPress = !(e.KeyValue >= 48 && e.KeyValue <= 57);
}

勾选New keyboard APIs: KeyEventArgs.SuppressKeyPress

The problem is that "Handled" doesn't take care of pending WM_CHAR messages already built up in the message queue - so setting Handled = true does not prevent a KeyPress from occurring.

In order not to break anyone who has currently got e.Handled = true, we needed to add a new property called SuppressKeyChar. If we went the other way, if "handling" a keydown suddenly started to actually work, we might break folks who accidentally had this set to true.

当您按下一个键时,一个字符已经附加到您的TextBox。然后你 运行 下面的代码,如果键代表一个数字,你再次附加它:

if (char.IsNumber((char)e.KeyCode)) {
    textBox1.Text += (char)e.KeyCode;
}

如果你想隐藏任何不是数字的键,你可以改用这个:

e.SuppressKeyPress = !char.IsNumber((char)e.KeyCode);

根据语法,我假设您正在使用 WinForms 来回答以下问题。

按键事件没有被抑制,所以它仍然像正常的按键事件一样工作,并将字符添加到框的文本中。此外,您自己再次将字符添加到文本中。

尝试抑制按键事件,以防按键被按下,而您不想允许。

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (!char.IsNumber((char)e.KeyCode))
    {
        e.SuppressKeyPress = true;
    }
}

试试这个代码只接受数字

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar))
        e.Handled = true;
}