Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling shortcuts from context menu

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?

like image 381
Mikhail Avatar asked Sep 06 '25 03:09

Mikhail


1 Answers

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);
like image 143
user2455025 Avatar answered Sep 09 '25 02:09

user2455025