简体   繁体   中英

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!!

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.

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);
     }
  }

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].

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM