I have a small form, which comes up when I press a button in a Windows Forms application.
I want to be able to close the form by pressing the escape key. How could I do this? I am not sure of the event to use. form_closing?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You can set a property on the form to do this for you if you have a button on the form that closes the form already.
Set the
CancelButtonproperty of the form to that button.If you don’t have a cancel button then you’ll need to add a
KeyDownhandler and check for the Esc key in that:You will also have to set the
KeyPreviewproperty to true.However, as Gargo points out in his answer this will mean that pressing Esc to abort an edit on a control in the dialog will also have the effect of closing the dialog. To avoid that override the
ProcessDialogKeymethod as follows: