MessageBox does not suppress keyboard Enter key

此生再无相见时 提交于 2021-02-10 18:25:40

问题


I have a button which, on Click event I made some validations upon some TextBoxes in my Form. If a TextBox does not pass the validation, then I force the Focus to it (user must enter some characters in that TextBox). My TextBox class already have some code to go to the next control if user will press Enter key.

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}");
        }
    }
}

Form's button click event:

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 ...
}

How do I stop the loosing focus on my textboxes when user hit Enter key in that MessageBox?


回答1:


A MessageBox can cause re-entrancy problems in some occasions. This is a classic one.

In this specific case, when the Enter key is pressed to send a confirmation to the dialog, the KeyUp event re-enters the message loop and is dispatched to the active control. The TextBox, here, because of this call: txtName.Focus();.

When this happens, the code in the TextBox's KeyUp event handler is triggered again, causing a SendKeys.Send("{TAB}");.

There are different ways to solve this. In this case, just use the TextBox.KeyDown event to both suppress the Enter key and move the focus:

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

Also, see (for example):

Pushing Enter in MessageBox triggers control KeyUp Event
MessageBox causes key handler to ignore SurpressKeyPress

as different methods to handle similar situations.



来源:https://stackoverflow.com/questions/59068664/messagebox-does-not-suppress-keyboard-enter-key

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!