How to close a form when pressing the evacuation key?

I have a small form that appears when I click a button in a Windows Forms application .

I want to be able to close the form by pressing the evacuation key. How can i do this? I'm not sure about using an event (form_closing?)?

+48
c # winforms
Aug 19 '10 at 22:20
source share
4 answers

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); } 
+91
Aug 19 '10 at 22:24
source share
โ€” -

The best way I've found is to override the ProcessDialogKey function. This method of canceling open control is still possible because the function is called only when the other control does not use the key pressed.

This is the same behavior as installing CancelButton. Using the KeyDown event always fires, and the form closes, even if it cancels editing the open editor.

 protected override bool ProcessDialogKey(Keys keyData) { if (Form.ModifierKeys == Keys.None && keyData == Keys.Escape) { this.Close(); return true; } return base.ProcessDialogKey(keyData); } 
+20
Jan 13 '15 at 15:45
source share

If you have a cancel button on the form, you can set the Form.CancelButton property to that button, and then pressing the escape button effectively "clicks the button."

If you donโ€™t have one, check the Form.KeyPreview property.

+5
Aug 19 '10 at 22:24
source share
 Button cancelBTN = new Button(); cancelBTN.Size = new Size(0, 0); cancelBTN.TabStop = false; this.Controls.Add(cancelBTN); this.CancelButton = cancelBTN; 
-2
Oct 25 '13 at 11:54 on
source share



All Articles