Friday, July 24, 2009

Capture the Enter key on WinForm Text-box

If you want to to capture the Enter key when you finish entering data in a .NET Framework WinForm text-box, and imitate clicking on a button, you should attach a KeyDown event to the text-box first.



In the KeyDown event handler code, use the following:

private void Text1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
       this.Close();
If you have a button on the form with DialogResult property set to OK, closing the form will be equal to clicking that button.

However, in this case, a simpler solution is to set the form's AcceptButton property to the name of your OK button. This will have the same effect.