Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 to be called no matter if any control has focus.

Thanks.

like image 434
Saeid Yazdani Avatar asked May 12 '11 11:05

Saeid Yazdani


People also ask

What is the Ctrl for close?

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.

How do you close something using the keyboard?

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.

Which property is used to exit close the form when pressed Esc?

Set the CancelButton property of the form to that button.


3 Answers

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.

like image 78
Anton Semenov Avatar answered Oct 04 '22 04:10

Anton Semenov


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);
}
like image 43
V4Vendetta Avatar answered Oct 04 '22 03:10

V4Vendetta


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.

like image 28
dandan78 Avatar answered Oct 04 '22 02:10

dandan78