简体   繁体   English

按Enter键而不是单击c#中的按钮

[英]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? 你可以从标题中了解到当你按下Enter键时按钮自动工作,如何用c#编写代码按Enter键而不是点击按钮? Thank you!! 谢谢!!

Is this WinForms? 这是WinForms吗? If so, you can set the AcceptButton of the form to be the button in question. 如果是这样,您可以将表单的AcceptButton设置为有问题的按钮。 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. 这样做会使按Enter的行为与使用鼠标单击按钮完全相同,但如果当前聚焦的元素不是也会捕获按键的其他元素,则只会产生该效果。

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. 当按钮具有焦点时,按下回车键不会导致KeyDown或KeyPress事件触发。 However, the KeyUp event fired. 但是,KeyUp事件被触发了。 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). 我相信,[space]是默认键,它会“点击”活动按钮(或勾选复选框等)。 You can always write method for events like OnKeyDown , OnKeyUp or similar. 您始终可以为OnKeyDownOnKeyUp或类似事件编写方法。 In these events you can check pushed key and do, whats clicking button is doing if this key is [enter]. 在这些事件中你可以检查按下的键,如果这个键是[enter],点击按钮是什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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