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

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

148972 次浏览

The Form has a KeyPreview property that you can use to intercept the keypress.

If you set your Form's AcceptButton property to one of the Buttons on the Form, you'll get that behaviour by default.

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.

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.

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.

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

As previously stated, set your form's AcceptButton property to one of its buttons AND set the DialogResult property for that button to DialogResult.OK, in order for the caller to know if the dialog was accepted or dismissed.

You can subscribe to the KeyUp event of the TextBox.

private void txtInput_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
DoSomething();
}
private void textBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
button.PerformClick();
}
  if (e.KeyCode.ToString() == "Return")
{
//do something
}

Simply use

this.Form.DefaultButton = MyButton.UniqueID;

**Put your button id in place of 'MyButton'.