If the form is modal, it's much better to have "Cancel" and/or "OK" ("Apply", "Accept", "Done") buttons used to finish modal state. Then you can handle Cancel (and/or Enter) by setting the properties
CancelButton
and/or
AcceptButton
of these buttons:
https://msdn.microsoft.com/en-us/library/system.windows.forms.form.cancelbutton(v=vs.110).aspx[
^],
https://msdn.microsoft.com/en-us/library/system.windows.forms.form.acceptbutton(v=vs.110).aspx[
^].
If the form is not modal, closing it by Escape would be a really, really bad idea. But of course you should be able to handle form keyboard event. The trick here is: the focus is usually taken by some other control on the form, so you should do something about it. This is done by setting the form property
KeyPreview
. Then you can handle the form event
PreviewKeyDown
or override the method
OnPreviewKeyDown
:
https://msdn.microsoft.com/en-us/library/system.windows.forms.form.keypreview(v=vs.110).aspx[
^],
https://msdn.microsoft.com/en-us/library/system.windows.forms.control.previewkeydown(v=vs.110).aspx[
^],
https://msdn.microsoft.com/en-us/library/system.windows.forms.control.onpreviewkeydown(v=vs.110).aspx[
^].
You mentioned that you don't want to do something for all forms. Of course. You should not repeat any code in different form classes; instead, always inherit some base form class with common functionality.
—SA