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

只愿长相守 提交于 2019-11-30 10:45:13
JaredPar

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.

bobbyalex

Use this to detect if the shift key is pressed:

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

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

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

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

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)
{ ... }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!