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

To add to @Willy David Jr answer: you also can use actual Key codes.

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

You can use the Keypress event. If you are just looking for the "Enter" keypress, then you probably don't care about modifier keys (such as Shift and/or Ctrl), which is why most would use KeyDown instead of Keypress. A second benefit is to answer the question that is almost always asked after implementing any of the other answers: "When I use the referenced code, why does pressing "Enter" cause a beep?" It is because the Keypress event needs to be handled. By using Keypress, you solve both in one place:

private void input_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == (char)Keys.Enter)
    {
        // Your logic here....
        e.Handled = true; //Handle the Keypress event (suppress the Beep)
    }
}

You can actually just say

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

Give this a shot...

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

Tags:

C#

Winforms

Enter