“转义”按钮关闭 C # 中的 Windows 窗体窗体

我试过以下方法:

private void Form1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if ((Keys) e.KeyValue == Keys.Escape)
this.Close();
}

但是没用。

然后我试了这个:

protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (e.KeyCode == Keys.Escape)
this.Close();
}

还是没有效果。

Windows 窗体属性上的 KeyPreview 设置为 true... 我做错了什么?

69511 次浏览

You should just be able to set the Form's CancelButton property to your Cancel button and then you won't need any code.

Assuming that you have a "Cancel" button, setting the form's CancelButton property (either in the designer or in code) should take care of this automatically. Just place the code to close in the Click event of the button.

By Escape button do you mean the Escape key? Judging by your code I think that's what you want. You could also try Application.Exit(), but Close should work. Do you have a worker thread? If a non-background thread is running this could keep the application open.

This will always work, regardless of proper event handler assignment, KeyPreview, CancelButton, etc:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
if (keyData == Keys.Escape) {
this.Close();
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}

The accepted answer indeed is correct, and I've used that approach several times. Suddenly, it would not work anymore, so I found it strange. Mostly because my breakpoint would not be hit for ESC key, but it would hit for other keys.

After debugging I found out that one of the controls from my form was overriding ProcessCmdKey method, with this code:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
// ...
if (keyData == (Keys.Escape))
{
Close();
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}

... and this was preventing my form from getting the ESC key (notice the return true). So make sure that no child controls are taking over your input.

You need add this to event "KeyUp".

    private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.Escape)
{
this.Close();
}
}

You set KeyPreview to true in your form options and then you add the Keypress event to it. In your keypress event you type the following:

private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 27)
{
Close();
}
}

key.Char == 27 is the value of escape in ASCII code.

You can also Trigger some other form.

E.g. trigger a Cancel-Button if you edit the Form CancelButton property and set the button Cancel.

In the code you treath the Cancel Button as follows to close the form:

    private void btnCancel_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Abort;
}