tags:

views:

500

answers:

4

I have tried the following:

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

...doesn't work.

Then i tried this:

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

..still nothing's working.

The KeyPreview on my windows form properties is set to true...what am i doing wrong?

+7  A: 

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

Shawn Steward
+3  A: 

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.

Adam Robinson
A: 

By Escape button do you mean Escape key? Judging by your code I think thats 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.

SwDevMan81
Any comments from the downvoter?
SwDevMan81
+4  A: 

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 base.ProcessCmdKey(ref msg, keyData);
    }
Hans Passant
thank you much! this was EXACTLY what i was looking for!!!
worked like a charm
Jared Updike