2

How could I make keyboard shortcuts which needs 3 or more keys to press?
Like Ctrl+Alt+S?

if (e.KeyCode == Keys.S && Control.ModifierKeys == Keys.Control && Control.ModifierKeys == Keys.Alt)
{
        SAVEc_FORCE();
}

but it don't work for me. Any suggestions?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
MineSky
  • 97
  • 1
  • 11
  • 4
    `Control.ModifierKeys == Keys.Control && Control.ModifierKeys == Keys.Alt` is always false because they are `key == a && key == b`. Read this post to learn how to use multiple ModifierKeys http://stackoverflow.com/questions/1434867/how-to-use-multiple-modifier-keys-in-c-sharp – Yeldar Kurmangaliyev May 28 '15 at 06:44
  • [ModifierKeys](https://msdn.microsoft.com/en-us/library/system.windows.forms.control.modifierkeys%28v=vs.110%29.aspx) returns a [Key bitmask](https://msdn.microsoft.com/en-us/library/system.windows.forms.keys(v=vs.110).aspx). It should be used as such. – user2864740 May 28 '15 at 06:45

2 Answers2

2

You have to combine the keys:

if (e.KeyCode == Keys.S && (Control.ModifierKeys == Keys.Control | Keys.Alt))

Keys are flags - a single value is made up of all the individual enum values (any you want). So when you press both Control and Alt at the same time, that corresponds to a value of Keys.Control | Keys.Alt. Of course, this means that neither Control.ModifierKeys == Keys.Control nor Control.ModifierKeys == Keys.Alt return true - even though ModifierKeys contains both of those, it's not equal to either of those.

As an extension, if you want to match Keys.Control regardless of the status of the remaining modifier keys, you can do this:

(Control.ModifierKeys & Keys.Control) == Keys.Control

or

Control.ModifierKeys.HasFlag(Keys.Control)
Luaan
  • 62,244
  • 7
  • 97
  • 116
  • `if (e.KeyCode == Keys.S && (Control.ModifierKeys == (Keys.Control | Keys.Alt)))` worked for me. Thanks! – MineSky May 28 '15 at 06:51
1

You have to code it this way:

if(e.KeyCode == Keys.S && e.Modifiers == (Keys.Control | Keys.Alt))

shruti1810
  • 3,920
  • 2
  • 16
  • 28