How to close a WinForm with keyboard while a control has focus
How can I close my C# WinForms program while there are some controls like treeviews, buttons and other stuff are present in it and they have focous and that could be they have same keyboard shortcut?
forexample in my treeview if I press ALT + ESC key, the nodes will be removed. but I want to be able by pressing ESC key the 'this.Close()' method 开发者_Go百科to be called no matter if any control has focus.
Thanks.
Set KeyPreview
property of your form to true. This allows you to handle keyboard message in form handlers before control handlers even if control has focus.
Maybe you could try this by overriding on the Form
protected override bool ProcessDialogKey(Keys keyData)
{
if (keyData == Keys.Escape)
{
this.Close();
return true;
}
else
return base.ProcessDialogKey(keyData);
}
You need to set the form's KeyPreview
property to true
. This will enable the form to capture keypresses before they are passed on to the controls on it, which makes it possible for you to intercept them and pass them on if you want to, or do something else, like closing the form with your key combination.
It's already built into Windows. Alt-F4 will close the foreground application. You don't need to do anything special to handle this yourself. If you want to close just one window, and not the whole application, such as in a MDI-style interface, then Ctrl-F4 will do the trick.
Set the KeyPreview
property of the Form to true(it will transfer the keyborad event to form before the controls.), and write code on the KeyXXX event, and check for ESC key and call this.close()
精彩评论