views:

2419

answers:

3

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.

I'm currently using the GetKeyState API to check for the SHIFT key. It works fine on my computer but users with non-English Windows say it doesn't work at all for them.

I also read that in the Win32 API when a context menu is opened there's a flag that indicates in the menu should show EXTENDEDVERBS. In C# the EventArgs for the Opening event doesn't contain (from what I can tell) a property indicating EXTENDEDVERBS or if any modifier keys are pressed.

Here's the code I'm using now inside the "Opening" event:

// SHIFT KEY is being held down
if (Convert.ToBoolean(GetKeyState(0x10) & 0x1000))
{
     _menuStrip.Items.Add(new ToolStripSeparator());

     ToolStripMenuItem log = new ToolStripMenuItem("Enable Debug Logging");
     log.Click += new EventHandler(log_Click);
     log.Checked = Settings.Setting.EnableDebugLogging;
     _menuStrip.Items.Add(log);
 }

If GetKeyState is the right way of doing it, is my code properly detecting the SHIFT key being pressed?

+5  A: 

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.

JaredPar
Unfortunately, the ContextMenu's parent in my code is a UserControl and the ModifierKeys property isn't available either for the UserControl or for the ContextMenu object.
Chris Thompson
@Chris - As Jared says it's static. I updated his answer with a link to msdn
Greg Dean
I didn't notice that. I was thinking that it was an instance property. I'll test it out.
Chris Thompson
+3  A: 

JaredPar is correct (i dont have enough rep to just comment)

Control.ModifierKeys

this is a static property of Control class, you should be able to use this.

http://msdn.microsoft.com/en-us/library/system.windows.forms.control.modifierkeys.aspx

Stan R.
+1 should help you get the rep you need
Greg Dean
+3  A: 

Why dont you use this to detect if shift key is pressed?

if ((Control.ModifierKeys & Keys.Shift) == Keys.Shift)
Bobby Alexander
By the time I typed this answer, Jared had already posted it. Sorry for the duplicate.
Bobby Alexander
Chris is right. The property should be available to you even though you are using a UserControl.
Bobby Alexander
This checks if the Shift key is pressed, which is what the original question wanted. The other answer checks if ONLY the Shift key is pressed.
adzm