Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Pushing Enter in MessageBox triggers control KeyUp Event

Tags:

c#

winforms

System: Windows7 Pro, Visual Studio 2010, C#

I have a textbox: textBox1 I set its event:

textBox1.KeyUp += new KeyEventHandler(textBox1_KeyUp);

private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        button1.PerformClick();
    }
}

private void button1_Click(object sender, EventArgs e)
{ 
    if (string.IsNullOrEmpty(textBox1.Text))
    {
        MessageBox.Show("Invalid data", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        return;
    } 
}

It works fine, the problem is, when the data entered is invalid, and thus the MessageBox is shown, when i hit ENTER on the MessageBox OK Button, it also triggers the textBox1_KeyUp, which causes the MessageBox to show up again. So, it triggers the MessageBox OK button, which causes it to disappear, and also triggers the textbox_keyUp which then causes the messagebox to show up again.

Thanks for your help.

like image 239
WoF_Angel Avatar asked Aug 21 '10 20:08

WoF_Angel


1 Answers

Yes, the message box responds to the key down event. So should your TextBox. Use the KeyDown event instead, problem solved. Also solves the annoying BEEP the user normally hears.

    private void textBox1_KeyDown(object sender, KeyEventArgs e) {
        if (e.KeyData == Keys.Enter) {
            button1.PerformClick();
            e.SuppressKeyPress = true;
        }
    }
like image 101
Hans Passant Avatar answered Oct 23 '22 06:10

Hans Passant