How to use multiple modifier keys in C#

44,874

Solution 1

if (e.KeyCode == Keys.C && e.Modifiers == (Keys.Control | Keys.Shift))
{
    //Do work
}
else if (e.KeyCode == Keys.V && e.Modifiers == Keys.Control)
{
    //Paste
}

Solution 2

Have you tried e.Modifiers == (Keys.Control | Keys.Shift)?

Solution 3

If you want to allow Ctrl and Shift then use the bitwise OR (as Keys is a Flags enum)

if (e.KeyCode == Keys.C && e.Modifiers == (Keys.Control | Keys.Shift))
{
    //Do work (if Ctrl-Shift-C is pressed, but not if Alt is pressed as well)
}
else if (e.KeyCode == Keys.V && e.Modifiers == Keys.Control)
{
    //Paste (if Ctrl is only modifier pressed)
}

This will fail if Alt is pressed as well

Solution 4

      if ((Keyboard.Modifiers & ModifierKeys.Shift | ModifierKeys.Control) > 0)
          Debugger.Launch();

Solution 5

Another way would be to add an invisible menu item, assign the Ctrl + Shift + C shortcut to it, and handle the event there.

Share:
44,874
jsmith
Author by

jsmith

Still learning a lot... Hopefully that will always be the case.

Updated on September 29, 2020

Comments

  • jsmith
    jsmith almost 4 years

    I am using a keydown event to detect keys pressed and have several key combinations for various operations.

    if (e.KeyCode == Keys.C && e.Modifiers == Keys.Control && e.Modifiers == Keys.Shift)
    {
        //Do work
    }
    else if (e.KeyCode == Keys.V && e.Modifiers == Keys.Control)
    {
        //Paste
    }
    

    For some reason the key combination in which I hit Ctrl + Shift + C is not working. I have re ordered them, and placed it at the top thinking it might be interference from the Ctrl + C, and even removed the Ctrl + C to see if it was causing a problem. It still does not work. I know it's probably something very simple, but can't quite grasp what it is. All of my 1 modifier + 1 key combination's work fine, as soon as I add a second modifier is when it no longer works.