C# Windows 窗体 - 输入按键激活提交按钮?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/164903/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Windows Forms - Enter keypress activates submit button?
提问by FlySwat
How can I capture enter keypresses anywhere on my form and force it to fire the submit button event?
如何在表单上的任何位置捕获输入按键并强制它触发提交按钮事件?
回答by itsmatt
The Form has a KeyPreviewproperty that you can use to intercept the keypress.
表单有一个KeyPreview属性,您可以使用它来拦截按键。
回答by Matt Hamilton
If you set your Form
's AcceptButton
property to one of the Button
s on the Form
, you'll get that behaviour by default.
如果您将Form
的AcceptButton
属性设置为 上的Button
s之一,则Form
默认情况下您将获得该行为。
Otherwise, set the KeyPreview
property to true
on the Form
and handle its KeyDown
event. You can check for the Enter
key and take the necessary action.
否则,将该KeyPreview
属性设置为true
onForm
并处理其KeyDown
事件。您可以检查Enter
密钥并采取必要的措施。
回答by Bill
Set the KeyPreview attribute on your form to True, then use the KeyPress event at your form level to detect the Enter key. On detection call whatever code you would have for the "submit" button.
将表单上的 KeyPreview 属性设置为 True,然后在表单级别使用 KeyPress 事件来检测 Enter 键。检测时调用“提交”按钮所需的任何代码。
回答by bouvard
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 Designerand note the few exceptions it outlines (multi-line text-boxes, etc.)
请参阅如何:使用设计器将 Windows 窗体按钮指定为接受按钮,并注意它概述的少数例外情况(多行文本框等)
回答by Sorin Comanescu
As previously stated, set your form's AcceptButtonproperty to one of its buttons AND set the DialogResultproperty for that button to DialogResult.OK, in order for the caller to know if the dialog was accepted or dismissed.
如前所述,将表单的AcceptButton属性设置为其按钮之一并将该按钮的DialogResult属性设置为DialogResult.OK,以便调用者知道对话框是被接受还是被解除。
回答by sanjeev
You can subscribe to the KeyUp
event of the TextBox
.
您可以订阅KeyUp
的事件TextBox
。
private void txtInput_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
DoSomething();
}
回答by ruvi
private void textBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
button.PerformClick();
}
回答by BenW
if (e.KeyCode.ToString() == "Return")
{
//do something
}
回答by Bino Kochumol Varghese
Simply use
只需使用
this.Form.DefaultButton = MyButton.UniqueID;
**Put your button id in place of 'MyButton'.
**将您的按钮 ID 替换为“MyButton”。