views:

66

answers:

2

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.

+1  A: 

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
        }
}
It Grunt
You don't need the cast here. Also this doesn't work properly when doing data binding on the textbox because the data source hasn't been updated at the point of the KeyDown and Keys.Return capture.
Mark Allanson
Thanks. You're right about the redundant cast. As to the issue with the data binding, can you add the keypress event after after the data binding has occurred? Or you could use a try/catch to swallow the exception right?
It Grunt
+1  A: 

You can drop this into the FormLoad event:

textBox1.KeyPress += (sndr, ev) => 
{
    if (ev.KeyChar.Equals((char)13))
    {
        // call your method for action on enter
        ev.Handled = true; // suppress default handling
    }
};
Nate Bross
This won't suppress default handling.
SLaks
All you need to add is `ev.Handled = true;` Updated post.
Nate Bross
Not the best way to check for enter key either.
Mark Allanson
What would be the best way then?
Nate Bross