[ACCEPTED]-Escape button to close Windows Forms form in C#-winforms

Accepted answer
Score: 204

This will always work, regardless of proper 1 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);
}
Score: 66

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

Score: 16

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

Score: 10

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

After 6 debugging I found out that one of the controls 5 from my form was overriding ProcessCmdKey method, with 4 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 3 form from getting the ESC key (notice the return true). So 2 make sure that no child controls are taking 1 over your input.

Score: 3

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

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

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

Score: 0

You need add this to event "KeyUp".

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

0

Score: 0

You can also Trigger some other form.

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

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

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

More Related questions