Licky
Licky

Reputation: 53

press Enter key instead of clicking on a button in c#

as you can understand from the title that how to when you press Enter key the button automatically work, how to write code in c# for pressing Enter key instead of clicking on button? Thank you!!

Upvotes: 3

Views: 22760

Answers (4)

user3763081
user3763081

Reputation: 43

For WPF set IsDefault="True" in XAML or use the button properties to set IsDefault checkbox.

Upvotes: 0

Marvin Thompson
Marvin Thompson

Reputation: 11

I had been trying to solve the same problem. When a button had focus, hitting the enter key did not result in the KeyDown or KeyPress event firing. However, the KeyUp event fired. Problem solved.

  private void CmdNoP_KeyUp(object sender, KeyEventArgs e) {
     // I do not understand why this works
     if (e.KeyCode == Keys.Return) {
        cmdNoP_MouseClick(sender, null);
     }
  }

Upvotes: 1

Ari
Ari

Reputation: 3127

I believe, [space] is default key, which would "click" active button (or check checkbox and so on). You can always write method for events like OnKeyDown, OnKeyUp or similar. In these events you can check pushed key and do, whats clicking button is doing if this key is [enter].

Upvotes: 0

Magnus Grindal Bakken
Magnus Grindal Bakken

Reputation: 2113

Is this WinForms? If so, you can set the AcceptButton of the form to be the button in question. Doing so will make pressing Enter behave exactly like clicking the button with the mouse, but it will only have that effect if the currently focused element isn't something else that will also capture the keypress.

Upvotes: 16

Related Questions