closing a form on escape

  • Thread starter Thread starter Yoavo
  • Start date Start date
Y

Yoavo

Hi,
I want to close my form when the user presses the Escape key.
I tried to catch the event KeyPress of the form but the program do not go
through this code.
I tried to catch the KeyPress event for several conrtrols in the dialog and
the event was caught, but I do not want to catch this event for every
control in the form.

What is the right way to close the form when the user presses Escape ?

Yoav.
 
Set the Form's CancelButton to a Button instance that has the
DialogResult property set to DialogResult.Cancel; this will cause the
form to be closed with a cancellation result.

Marc
 
Yoavo said:
Hi,
I want to close my form when the user presses the Escape key.
I tried to catch the event KeyPress of the form but the program do not go
through this code.
I tried to catch the KeyPress event for several conrtrols in the dialog and
the event was caught, but I do not want to catch this event for every
control in the form.

What is the right way to close the form when the user presses Escape ?

If the form is a dialog, then in probably some sort of a Close or
Cancel button (it is a good idea to include at least Close, anyway,
per the UI guidelines). If so, you can set the form's CancelButton
property to that button, and it will be automatically pressed (and its
Click event handler called) when the user presses ESC. This is the
preferred way.

If you'd really rather have a form without Close, then you should set
its KeyPreview property to true - then, it will receive any key event
before it reaches the child controls.
 
Hi,
I want to close my form when the user presses the Escape key.
I tried to catch the event KeyPress of the form but the program do not go
through this code.
I tried to catch the KeyPress event for several conrtrols in the dialog and
the event was caught, but I do not want to catch this event for every
control in the form.

What is the right way to close the form when the user presses Escape ?

Try using the KeyDown Form event. Works for me.

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
Application.Exit();
}
 
Hi,
I want to close my form when the user presses the Escape key.
I tried to catch the event KeyPress of the form but the program do not go
through this code.
I tried to catch the KeyPress event for several conrtrols in the dialog and
the event was caught, but I do not want to catch this event for every
control in the form.

What is the right way to close the form when the user presses Escape ?

Yoav.

Hi,

You can use Form.ProcessCmdKey to handle any control key, like ESC,
enter, etc.
This allow you to decide what to do with more control
 
Back
Top