Hi,
I would like to find a way in C# so that, when the user presses the “Esc” key, the form closes; the problem is that I have a lot of controls in the form.
At the beginning I have tried with the following form event handler:
But I have realized that it functions only if there are no controls in the form.
Suppose that you have three Buttons in the form (btn1, btn2 and btn3).
The fastest way (with the minimum number of code lines) I have found to close the form pressing the Esc key is the following one:
Have I to add a
statement for EVERY control in the form??? (suppose you have 100 controls... It's not so nice!!!)
Do you know if there is a faster way (with a lower number of code lines) to do that?
Thank you very much
I would like to find a way in C# so that, when the user presses the “Esc” key, the form closes; the problem is that I have a lot of controls in the form.
At the beginning I have tried with the following form event handler:
Code:
protected override void OnKeyPress(KeyPressEventArgs e)
{
base.OnKeyPress(e);
if (e.KeyChar == (char)Keys.Escape)
Close();
}
But I have realized that it functions only if there are no controls in the form.
Suppose that you have three Buttons in the form (btn1, btn2 and btn3).
The fastest way (with the minimum number of code lines) I have found to close the form pressing the Esc key is the following one:
Code:
…
btn1.KeyPress += new KeyPressEventHandler(control_KeyPress);
…
btn2.KeyPress += new KeyPressEventHandler(control_KeyPress);
…
btn3.KeyPress += new KeyPressEventHandler(control_KeyPress);
…
…
…
void control_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Escape)
Close();
}
Have I to add a
Code:
Control_i.KeyPress += new KeyPressEventHandler(control_KeyPress);
statement for EVERY control in the form??? (suppose you have 100 controls... It's not so nice!!!)
Do you know if there is a faster way (with a lower number of code lines) to do that?
Thank you very much