How do I tell when the enter key is pressed in a TextBox?

Jon picture Jon · Aug 4, 2012 · Viewed 40.8k times · Source

Basically, I want to be able to trigger an event when the ENTER key is pressed. I tried this already:

private void input_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Equals("{ENTER}"))
        {
            MessageBox.Show("Pressed enter.");
        }
    }

But the MessageBox never shows up. How can I do this?

Answer

Chris Gessler picture Chris Gessler · Aug 4, 2012

Give this a shot...

private void input_KeyDown(object sender, KeyEventArgs e) 
{                        
    if(e.KeyData == Keys.Enter)   
    {  
        MessageBox.Show("Pressed enter.");  
    }             
}