100

I have tried the following:

private void Form1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
    if ((Keys) e.KeyValue == Keys.Escape)
        this.Close();
}

But it doesn't work.

Then I tried this:

protected override void OnKeyDown(KeyEventArgs e)
{
    base.OnKeyDown(e);
    if (e.KeyCode == Keys.Escape)
        this.Close();
}

And still nothing's working.

The KeyPreview on my Windows Forms form properties is set to true... What am I doing wrong?

4
  • 1
    Have you tried setting a breakpoint in those methods? Is the event handler even firing? Commented Feb 18, 2010 at 18:08
  • 1
    Don't name your cancel button like the form property 'CancelButton'. Otherwise it seems that you can't set the CancelButton. Commented Aug 18, 2011 at 8:42
  • @SteveDanner, event doesn't get triggered. probably declaration in InitializeComponent() is missing. Commented Oct 12, 2011 at 14:28
  • I think that the reason it doesn't work is beacause that other controls inside the form got the focus...
    – itsho
    Commented Apr 4, 2012 at 12:17

8 Answers 8

207

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);
}
6
  • 12
    -1, using of Form's CancelButton property is the correct way.
    – ABCD
    Commented Feb 6, 2013 at 12:05
  • 14
    Ugh, the 1980s called, they want their dialog box back. Commented Feb 6, 2013 at 12:39
  • 9
    You can only use a CancelButton property of the form if the form has an actual Button on it (or an IButtonControl interface object).
    – David
    Commented Dec 18, 2013 at 17:45
  • 2
    What makes this the preferred method over the CancelButton property?
    – AdamMc331
    Commented Aug 19, 2015 at 14:29
  • 3
    This option is good. CancelButton requires additional visible 'Cancel' button on form. This is redundant render + code + etc
    – V319
    Commented Jan 3, 2018 at 9:26
67

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

3
  • 3
    I did that but it's not fired when I press esc, why? Commented May 20, 2014 at 13:57
  • This worked great for me. Much better for small forms.
    – knut
    Commented Jul 8, 2016 at 8:53
  • Keep in mind that the button you set the CancelButton to needs to be visible.
    – Sal
    Commented Jun 13, 2021 at 5:12
16

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.

10

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.

2
  • Off the top of my head, not sure if you need to set form KeyPreview to true - msdn.microsoft.com/en-us/library/…
    – Andez
    Commented Jan 12, 2015 at 17:21
  • I seem to be encountering this issue with ListView controls on my winform. I wonder if it is the ListView where you saw the problem too?
    – raddevus
    Commented Nov 12, 2018 at 14:27
3

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.

2
  • This is a good workaround to the issue. I have a form with ListView controls on it and in that case they seem to swallow the CancelButton (when Esc is pressed). I added this code and it fixed the issue.
    – raddevus
    Commented Nov 12, 2018 at 14:30
  • This works, but you need to set KeyPreview to true for the form
    – Maris B.
    Commented May 27, 2021 at 12:26
0

You need add this to event "KeyUp".

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

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

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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.