You can set a property on the form to do this for you if you have a button on the form that already closes the form.
Set the CancelButton form property for this button.
Gets or sets the button control that is pressed when the user presses the Esc key .
If you do not have a cancel button, you need to add a KeyDown handler and check the following for the Esc key:
private void Form_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Escape) { this.Close(); } }
You also need to set the KeyPreview property to true.
Gets or sets a value indicating whether the form will receive key events before the event is passed to the focus control.
However, as Gargo points out in the answer, this will mean that pressing Esc to interrupt editing the control in the dialog box will also have the effect of closing the dialog. To avoid overriding the ProcessDialogKey method as follows:
protected override bool ProcessDialogKey(Keys keyData) { if (Form.ModifierKeys == Keys.None && keyData == Keys.Escape) { this.Close(); return true; } return base.ProcessDialogKey(keyData); }
ChrisF Aug 19 '10 at 22:24 2010-08-19 22:24
source share