I have tried the following:
private void Form1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if ((Keys) e.KeyValue == Keys.Escape)
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.
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 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;
}
You need add this to event "KeyUp".
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.Escape)
{
this.Close();
}
}
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.