Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you add an ESC Key shortcut?

Tags:

c#

.net

winforms

I have a Menustrip Item on my Form, and it closes my Form when I press it. I want to make the shortcut key for my MenuStrip Item Esc, but in the "ShorcutKey" settings, it doesn't have an option for Esc, is there any way I can make it do that it is Esc? I have to make it show on the MenuStrip Item that Esc is the shortcut key.

Doing this does NOT work:

menuStripItem.ShortcutKeys = Keys.Escape;
like image 295
Dozer789 Avatar asked Aug 14 '13 15:08

Dozer789


People also ask

Is there a shortcut for Esc?

While you cannot bring back a missing physical Escape key, you can replicate its functionality with a little help from a nifty universal keyboard shortcut, and here's how: To invoke Escape, press Command + period (.) on the keyboard. This useful system-wide synonym for Escape works across iOS, iPadOS, and macOS.

What can I use instead of Esc button?

If you have an American English keyboard, pressing Ctrl-[ (control plus left square bracket) is equivalent to pressing Esc. This provides an easy way to exit from insert mode.

How do you add shortcut keys?

To assign a keyboard shortcut do the following: Begin keyboard shortcuts with CTRL or a function key. Press the TAB key repeatedly until the cursor is in the Press new shortcut key box. Press the combination of keys that you want to assign.


1 Answers

Winforms is picky about the shortcut keystroke you select. The rule is that it must be a function key (F1-F12) or another key with either Keys.Control or Keys.Alt included. The bigger intention here is that you can't accidentally replace a normal key that might be used in, say, a TextBox. The Escape key normally operates the cancel button of a dialog.

Keys.Escape is rather special; Alt+Escape and Ctrl+Escape cannot work, as they are global shortcut keys in Windows.

So you can't use the ShortcutKeys property; you have to recognize the Escape key differently. Easily done in your Form class by overriding the ProcessCmdKey() method. Paste this code into your form:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
    if (keyData == Keys.Escape) {
        this.Close();
        return true;
    }
    return base.ProcessCmdKey(ref msg, keyData);
}
like image 193
Hans Passant Avatar answered Sep 19 '22 10:09

Hans Passant