.NET TextBox - Handling the Enter Key

Viewed 57008

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.

5 Answers

In cases you want some button to handle Enter while program is executing, just point the AcceptButton property of the form to the button.

E.g.: this.AcceptButton = StartBtn;

Set the KeyPress event like this:

this.tMRPpart.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.tMRPpart_KeyPress);

Then you can perform actions including detecting the 'enter' key in the event -

private void tMRPpart_KeyPress(object sender, KeyPressEventArgs e)
{
    // force any lower case characters into capitals
    if (e.KeyChar >= 'a' && e.KeyChar <= 'z')
        e.KeyChar -= (char)32;

    // If user presses return, tab to next tab stop
    if (e.KeyChar == (char)Keys.Return)
    {
        if (sender is Control)
        {
            // Move to next control
            SelectNextControl((Control)sender, true, true, true, true);
        }
    }
}

In my case I wanted the application to tab to the next field if the user pressed enter.

Related