为什么 KeyDown 事件处理程序在 C# 中的 MessageBox.Show() 之后无法正常工作?那我怎么提醒用户呢?

Why KeyDown event handler not working properly after MessageBox.Show() in C#? Then how can I alert the User?

仅当我注释掉 MessageBox.Show().

时,此代码才能正常工作
private void textBox1_KeyDown( object sender, KeyEventArgs e ) {
    if( textBox1.Text.Contains('.') && ( e.KeyCode == Keys.Decimal || e.KeyCode == Keys.OemPeriod ) ) {
        MessageBox.Show("More than one decimal point!");
        e.SuppressKeyPress = true;
    }
}

这是什么原因?以及如何提醒用户?

编辑

那么我如何提醒错误的按键操作?

当您显示消息框时,它会离开 TextBox 的焦点,并且您的代码 e.SuppressKeyPress = true 不会在那个时候执行。

您应该在处理完输入后放置 MessageBox

e.SuppressKeyPress = true;
MessageBox.Show("More than one decimal point!");

你应该试试这个

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if(textBox1.Text.Contains('.') && e.KeyChar == '.')
    {
        e.Handled = true;
        MessageBox.Show("More than one decimal point!");
    }
}

最好在 KeyPress 而不是 KeyDown

当我发现我有一个很棒的页面说 difference between the KeyDown and KeyPress events in .net