Escape button to close Windows Forms form in C#

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

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.

Tags:

C#

Winforms