views:

662

answers:

4

Often when using software these days, the ESC key will close a dialog without persisting any changes I've made. I like that especially because even though the dialog may have a cancel button on it, I don't necessarily want to reach for the mouse or tab over to the cancel button. It's a nice clean way of saying "Oops, didn't meant to do that!" to the software. In fact, I find I get annoyed with software that doesn't implement this feature and I can't believe that it's not already done under the hood of Winforms - seems intuitive to me...

I have looked at hooking into the Form KeyPress event, or trying to simulate a "Cancel" DialogResult etc. There seem to be a number of ways of going about this...

So the question is: What is the cleanest way of going about binding the ESC key to close the dialog without saving any changes?

Any help from those that have experience in this is much appreciated!

+12  A: 

Set the CancelButton property of the form to reference your Cancel button.

RichieHindle
There is also a corresponding "AcceptButton" for the enter key. The advantage of this answer method is that there's more to hooking enter and escape than keypresses - using this method will also render the correct visual hints on the buttons (for example, the AcceptButton gets a thicker border).
stusmith
Don't forget to also set the DialogResult property of your cancel and OK buttons.
NascarEd
+4  A: 

You can also set the CancelButton property of the form to the cancel button:

this.CancelButton = this.cancelButton;

In Visual Studio you can set this via the Properties of the form and the code is added to the Form.Designer.cs file

ChrisF
A: 

To a certain extent it depends on your development environment - in .NET its built in (as it was in vb.old), forms has a "Cancel Button" property "If this property is set, the button is 'clicked' whenever the user presses the 'ESC' key."

There is a corresponding "AcceptButton" property for the 'ENTER' key.

From memory, standard message and dialog boxes will follow the above logic by default - though of course one can specify the default button for a message box where you don't want stuff to happen without the user positively asserting that that's what they want to do.

Murph
A: 

but I do not want to display the "Cancel" button :(

Duggi