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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With