C# - Detecting if the SHIFT key is held when opening a context menu

后端 未结 5 2043
感情败类
感情败类 2021-01-01 08:24

In my C# application I want to display a context menu, but I want to add special options to the menu if the SHIFT key is being held down when the context menu is opened.

相关标签:
5条回答
  • 2021-01-01 08:56

    In silverlight, at least in latest versions, you must use:

    if(Keyboard.Modifiers == ModifierKeys.Shift) {
        ...
    }
    
    0 讨论(0)
  • 2021-01-01 08:58

    You can use the ModifierKeys static property on control to determine if the shift key is being held.

    if (Control.ModifierKeys == Keys.Shift ) { 
      ...
    }
    

    This is a flag style enum though so depending on your situation you may want to do more rigorous testing.

    Also note that this will check to see if the Shift key is held at the moment you check the value. Not the moment when the menu open was initiated. That may not be a significant difference for your application but it's worth noting.

    0 讨论(0)
  • 2021-01-01 09:13

    It's actually much simpler than any of that

                if( Keyboard.IsKeyDown(Key.LeftCtrl) || 
                    Keyboard.IsKeyDown(Key.RightCtrl) ||
                    Keyboard.IsKeyDown(Key.LeftAlt) ||
                    Keyboard.IsKeyDown(Key.RightAlt) ||
                    Keyboard.IsKeyDown(Key.LeftShift) ||
                    Keyboard.IsKeyDown(Key.RightShift))
                {
                    /** do something */
                }
    

    Just make sure your project references PresentationCore and WindowsBase

    0 讨论(0)
  • 2021-01-01 09:22

    Keyboard.Modifiers also works with actual WPF projects!
    Also I would recommend it's use over Keyboard.GetKeyStates because the latter uses triggering and may not reflect the real key state.

    Also be aware that this will trigger ONLY if the shift modifier key is down and nothing else:

    if(Keyboard.Modifiers == ModifierKeys.Shift)
    { ... }
    

    If you just want to detect if the shift key is down, whether another modifier key is pressed or not, use this one:

    if((Keyboard.Modifiers & ModifierKeys.Shift) == ModifierKeys.Shift)
    { ... }
    
    0 讨论(0)
  • 2021-01-01 09:23

    Use this to detect if the shift key is pressed:

    if ((Control.ModifierKeys & Keys.Shift) == Keys.Shift) 
    
    0 讨论(0)
提交回复
热议问题