.NET TextBox - Handling the Enter Key

Mark Allanson picture Mark Allanson · Aug 24, 2010 · Viewed 46.8k times · Source

What is definitively the best way of performing an action based on the user's input of the Enter key (Keys.Enter) in a .NET TextBox, assuming ownership of the key input that leads to suppression of the Enter key to the TextBox itself (e.Handled = true)?

Assume for the purposes of this question that the desired behavior is not to depress the default button of the form, but rather some other custom processing that should occur.

Answer

It Grunt picture It Grunt · Aug 24, 2010

Add a keypress event and trap the enter key

Programmatically it looks kinda like this:

//add the handler to the textbox
this.textBox1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(CheckEnterKeyPress);

Then Add a handler in code...

private void CheckEnterKeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
        if (e.KeyChar == (char)Keys.Return)

        {
           // Then Do your Thang
        }
}