Escape button to close Windows Forms form in C#

Solution 1:

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);
}

Solution 2:

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

Solution 3:

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.

Solution 4:

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.

Solution 5:

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.