MessageBox 不抑制键盘回车键

MessageBox does not suppress keyboard Enter key

我有一个按钮,在 Click 事件中,我对 Form 中的某些 TextBox 进行了一些验证。 如果 TextBox 没有通过验证,那么我会强制使用 Focus(用户必须在 TextBox 中输入一些字符)。如果用户按 Enter 键,我的 TextBox class 已经有一些代码可以转到下一个控件。

MyTextBox.cs class

public class MyTextBox : TextBox
{
    public MyTextBox(){
        KeyUp += MyTextBox_KeyUp;
        KeyDown += MyTextBox_KeyDown;
    }

    private void MyTextBox_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            // This will suppress Blink sound
            e.SuppressKeyPress = true;
        }
    }

    private void MyTextBox_KeyUp(object sender, KeyEventArgs e)
    {
        if ((e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Return))
        {
            // This will go to the next control if Enter will be pressed.
            SendKeys.Send("{TAB}");
        }
    }
}

窗体的按钮点击事件:

private void BtnPrint_Click(object sender, EventArgs e){
    // txtName is based on MyTextBox class
    if(txtName.Text.Length == 0){
        MessageBox.Show("Name field could not be empty! Please fill the Name!", "Error Message",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
        // If I Click the OK button, txtName will stay focused in the next line,
        // but if I press Enter key, it will go to the next control.
        txtName.Focus();
        return;
    }
    // Some other validations ...
    // Calling printing method ...
}

当用户按下 Enter 键时,如何停止对我的文本框的关注 MessageBox?

MessageBox 在某些情况下会导致重入问题。这是一个经典的。

在这种特定情况下,当按下 Enter 键向对话框发送确认时,KeyUp 事件 重新输入 消息循环并被分派到活动控件。 TextBox,在这里,因为这个调用:txtName.Focus();

发生这种情况时,TextBox 的 KeyUp 事件处理程序中的代码再次被触发,导致 SendKeys.Send("{TAB}");

有多种方法可以解决这个问题。在这种情况下,只需使用 TextBox.KeyDown 事件来抑制 Enter 键并移动焦点:

private void MyTextBox_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        e.SuppressKeyPress = true;
        SendKeys.Send("{TAB}");
    }
}

另见(例如):

Pushing Enter in MessageBox triggers control KeyUp Event

作为处理类似情况的不同方法。