I had the same problem and did not want to reprogram the access functions the ContextMenuStrip
already offers me.
The big problem about that is, when I expand or change the ContextMenuStrip
items, I have to alter or change my own Key-Events. My aim was to bypass this and redirect the global shortcut keys to the ContextMenuStrip
to perform the click by code.
Firstly, I built a method that gets me all ToolStripMenuItems
of the ContextMenuStrip
in one list recursively:
private List<ToolStripMenuItem> getContextMenuItems(ToolStripItemCollection items)
{
List<ToolStripMenuItem> result = new List<ToolStripMenuItem>();
foreach (ToolStripMenuItem item in items)
{
result.Add(item);
if (item.HasDropDownItems)
{
result.AddRange(this.getContextMenuItems(item.DropDownItems));
}
}
return result;
}
Then I set up the KeyUp event to catch my keys on a wrapper control. this.cmsCellRightClick
is my ContextMenuStrip
:
private void xxxxx_KeyUp(object sender, KeyEventArgs e)
{
Keys pressed = e.KeyCode;
if (e.Control) pressed = pressed | Keys.Control;
if (e.Shift) pressed = pressed | Keys.Shift;
if (e.Alt) pressed = pressed | Keys.Alt;
ToolStripMenuItem actionItem = this.getContextMenuItems(this.cmsCellRightClick.Items)
.Where(x => x.ShortcutKeys == pressed).FirstOrDefault();
if (actionItem != null)
{
actionItem.PerformClick();
}
e.SuppressKeyPress = true;
}
The result is it will catch my keystrokes and send them to my ContextMenuStrip
and perform the click, even when the ContextMenuStrip
is hidden / not open.