Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows Forms - Enter keypress activates submit button?

Tags:

c#

winforms

How can I capture enter keypresses anywhere on my form and force it to fire the submit button event?

like image 242
FlySwat Avatar asked Oct 02 '08 22:10

FlySwat


4 Answers

If you set your Form's AcceptButton property to one of the Buttons on the Form, you'll get that behaviour by default.

Otherwise, set the KeyPreview property to true on the Form and handle its KeyDown event. You can check for the Enter key and take the necessary action.

like image 66
Matt Hamilton Avatar answered Oct 18 '22 21:10

Matt Hamilton


private void textBox_KeyDown(object sender, KeyEventArgs e) 
{
    if (e.KeyCode == Keys.Enter)
        button.PerformClick();
}
like image 32
ruvi Avatar answered Oct 18 '22 20:10

ruvi


You can designate a button as the "AcceptButton" in the Form's properties and that will catch any "Enter" keypresses on the form and route them to that control.

See How to: Designate a Windows Forms Button as the Accept Button Using the Designer and note the few exceptions it outlines (multi-line text-boxes, etc.)

like image 24
bouvard Avatar answered Oct 18 '22 22:10

bouvard


As previously stated, set your form's AcceptButton property to one of its buttons AND set the DialogResult property for that button to DialogResult.OK, in order for the caller to know if the dialog was accepted or dismissed.

like image 11
Sorin Comanescu Avatar answered Oct 18 '22 20:10

Sorin Comanescu