简体   繁体   English

Windows 窗体 - 输入按键激活提交按钮?

[英]Windows Forms - Enter keypress activates submit button?

如何在表单上的任何位置捕获输入按键并强制它触发提交按钮事件?

If you set your Form 's AcceptButton property to one of the Button s on the Form , you'll get that behaviour by default.如果您设置FormAcceptButton属性的一个Button S中的Form ,你会得到默认这种行为。

Otherwise, set the KeyPreview property to true on the Form and handle its KeyDown event.否则,将Form上的KeyPreview属性设置为true并处理其KeyDown事件。 You can check for the Enter key and take the necessary action.您可以检查Enter键并采取必要的操作。

private void textBox_KeyDown(object sender, KeyEventArgs e) 
{
    if (e.KeyCode == Keys.Enter)
        button.PerformClick();
}

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.您可以在表单的属性中将一个按钮指定为“AcceptButton”,这将捕获表单上的任何“Enter”按键并将它们路由到该控件。

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.)请参阅如何:使用设计器将 Windows 窗体按钮指定为接受按钮,并注意它概述的少数例外情况(多行文本框等)

如前所述,将表单的AcceptButton属性设置为其按钮之一并将该按钮的DialogResult属性设置为DialogResult.OK ,以便调用者知道对话框是被接受还是被解除。

You can subscribe to the KeyUp event of the TextBox .您可以订阅TextBoxKeyUp事件。

private void txtInput_KeyUp(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
       DoSomething();
}

表单有一个KeyPreview属性,您可以使用它来拦截按键。

Simply use只需使用

this.Form.DefaultButton = MyButton.UniqueID;  

**Put your button id in place of 'MyButton'. **将您的按钮 ID 替换为“MyButton”。

Set the KeyPreview attribute on your form to True, then use the KeyPress event at your form level to detect the Enter key.将表单上的 KeyPreview 属性设置为 True,然后在表单级别使用 KeyPress 事件来检测 Enter 键。 On detection call whatever code you would have for the "submit" button.检测时调用“提交”按钮所需的任何代码。

  if (e.KeyCode.ToString() == "Return")
  { 
      //do something
  }

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

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