I need to close an mdi child
with Esc key. I tried using keydown
and keypress
events, but i cant even get the form respond to those events when pressing any key.
try this
private void Form_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
{
this.Close();
}
}
or make use of
Form.CancelButton Property
- Gets or sets the button control that is clicked when the user presses the ESC key.
Set the Property of the Form KeyPreview=True
and go with Keydown Event
if (e.KeyCode == Keys.Escape){
this.Close();
}
If your MDI Form has Close
button, then you can assign CancelButton
property with the ID of Close
button in your Form.
So when you press ESC key, it will call Close
button click.
More : CancelButton
First you must set the Form.KeyPreview = true
and you must know what is the Difference between the KeyUp and KeyDown Event
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
{
this.Close();
}
}
and if you want the KeyPress Event
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 27)
{
this.Close();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.