Reputation: 21749
I have a Windows Form shown as a model dialog. It has a context menu of class ContextMenuStrip
. I set shortcuts to several items in the context menu. But this shortcuts works only when context menu is shown. How to make them work even if the context menu is not activated?
The only way I know is to handle KeyPress
event of the form, iterate recursively through all the items in the context menu and compare its ShortcutKeys
property with the actual key pressed. If the match, manually call OnClick
event for this item. Any better ideas?
Upvotes: 3
Views: 9150
Reputation: 39
Use the ToolStripMenuItem.ShortCutKeys property, so that you no need to iterate and call the event handlers.
Sample Code:
ContextMenuStrip _contextMenuStrip = new ContextMenuStrip();
var menuItem = new ToolStripMenuItem("Copy");
menuItem.ShortcutKeys = Keys.Control | Keys.C;
_contextMenuStrip.Items.Add(menuItem);
Upvotes: 4
Reputation: 21749
Finally, I've implemented manual iteration in the KeyPressed
event handler:
Action<ToolStripMenuItem> check_shortcut = null;
check_shortcut = (node) =>
{
if (node.ShortcutKeys == e.KeyData)
{
node.PerformClick();
}
foreach (ToolStripMenuItem child in node.DropDownItems)
{
check_shortcut(child);
}
};
foreach (ToolStripMenuItem item in MyContextMenuStrip.Items)
{
check_shortcut(item);
}
Upvotes: 1
Reputation: 343
Are you opening the ContextMenuStrip
in code or is the ContextMenuStrip
property of the Form
set to the ContextMenuStrip
you created? If it's being opened in code, are you able to set the Form
property instead? That should let you do the shortcut without having to open the menu first.
Upvotes: 0