Vali Maties
Vali Maties

Reputation: 399

MessageBox does not suppress keyboard Enter key

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?

Upvotes: 1

Views: 1494

Answers (1)

Jimi
Jimi

Reputation: 32223

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.

Upvotes: 1

Related Questions