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 to be called no matter if any control has focus.
Thanks.
Alternatively referred to as Control+W and C-w, ^w, Ctrl+W is a keyboard shortcut often used to close a program, window, tab, or document. How to use the Ctrl+W keyboard shortcut.
Alt + F4 is a keyboard shortcut that completely closes the application you're currently using on your computer. Alt + F4 differs slightly from Ctrl + F4, which closes the current tab or window of the program you're currently using.
Set the CancelButton property of the form to that button.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With