'How to make a form close when pressing the escape key?

I have a small form, which comes up when I press a button in a Windows Forms application.

I want to be able to close the form by pressing the escape key. How could I do this? I am not sure of the event to use. form_closing?



Solution 1:[1]

The best way i found is to override the "ProcessDialogKey" function. This way canceling an open control is still possible because the function is only called when no other control uses the pressed Key.

This is the same behaviour as setting the CancelButton property. Using the KeyDown Event fires always and thus the form will close even when it should cancel the edit of an open editor.

protected override bool ProcessDialogKey(Keys keyData)
{
    if (Form.ModifierKeys == Keys.None && keyData == Keys.Escape)
    {
        this.Close();
        return true;
    }
    return base.ProcessDialogKey(keyData);
}

Solution 2:[2]

Button cancelBTN = new Button();
cancelBTN.Size = new Size(0, 0);
cancelBTN.TabStop = false;
this.Controls.Add(cancelBTN);
this.CancelButton = cancelBTN;

Solution 3:[3]

If you have a cancel button on your form, you can set the Form.CancelButton property to that button and then pressing escape will effectively 'click the button'.

If you don't have such a button, check out the Form.KeyPreview property.

Solution 4:[4]

Paste this code into the "On Key Down" Property of your form, also make sure you set "Key Preview" Property to "Yes".

If KeyCode = vbKeyEscape Then DoCmd.Close acForm, "YOUR FORM NAME"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 George Brighton
Solution 3 Will A
Solution 4 fcdt