Windows Forms - Enter keypress activates submit button?

How can I capture click input anywhere on my form and make it fire the submit button event?

+69
c # winforms
Oct 02 '08 at 22:28
source share
9 answers

If you set the FormButton property to one of the buttons on the form, you will get this default behavior.

Otherwise, set the KeyPreview property to True on the form and handle its KeyDown event. You can check the Enter key and take the necessary actions.

+152
Oct 02 '08 at
source share

You can designate the button as "AcceptButton" in the form properties, and it will capture any "Enter" clicks on the form and direct them to this control.

See this MSDN article and note the few exceptions it describes (multi-line text fields, etc.)

+20
Oct 02 '08 at 22:40
source share
private void textBox_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter){ button.PerformClick(); } } 
+11
Jul 25 '13 at 8:36
source share

As stated above, set the AcceptButton property of one of its buttons for your form AND set the DialogResult property of this button to DialogResult.OK so that the caller knows whether the dialog was accepted or rejected.

+8
Jun 10 '09 at 11:25
source share

You can subscribe to the KeyUp event in the text box.

 private void txtInput_KeyUp(object sender, KeyEventArgs e) { if(e.KeyCode == Keys.Enter) DoSomething(); } 
+5
Apr 20 '13 at 19:09
source share

The form has a KeyPreview property that you can use to intercept key presses.

+2
02 Oct '08 at
source share

Set the KeyPreview attribute in your form to True, then use the KeyPress event at the level of your form to detect the Enter key. Upon detection, call any code that you would specify for the send button.

0
02 Oct '08 at
source share
  if (e.KeyCode.ToString() == "Return") { //do something } 
0
May 29 '15 at 5:02
source share

Just use

 this.Form.DefaultButton = MyButton.UniqueID; 

** Put your button id instead of "MyButton".

0
Mar 03 '16 at 13:39
source share



All Articles