Click here to Skip to main content
15,913,140 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
How can I close my active windows form without using mouse click, but by using keyboard keys (shortcut/accelerated keys) in C#?
Posted
Updated 22-Nov-10 23:44pm
v2
Comments
JF2015 23-Nov-10 5:44am    
Edited for spelling.

You just need to subscribe the KeyDown event handler and then you will get an event when a key is pressed. In this event you can check which key was pressed. If for example you want to close your form when "Return" is pressed, then you might use:

C#
private void KeyDown(object sender, KeyEventArgs e)
{
  if (e.KeyCode == Keys.Return)
    this.Close();
}
 
Share this answer
 
v2
Comments
Dalek Dave 23-Nov-10 5:53am    
Good Call.
In Page Keydown or keyup event write code like this,
For VB,
If e.KeyCode = Keys.Esc Then
Me.close()
End If

For C#,
this.Close();
 
Share this answer
 
v3
Hi,

Just use your form keydown event.
private void form_KeyDown(object sender, KeyEventArgs e)
{
 if(e.KeyCode == Keys.Escape)
 {
  // use message box if you need.
  this.close();
 } 
}


Cheers :)
 
Share this answer
 
Try ALT+F4 (or CTRL+F4 for a mdi child).
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900