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.
In silverlight, at least in latest versions, you must use:
if(Keyboard.Modifiers == ModifierKeys.Shift) {
...
}
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.
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
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)
{ ... }
Use this to detect if the shift key is pressed:
if ((Control.ModifierKeys & Keys.Shift) == Keys.Shift)