Is there a way to show ContextMenu and block further execution until the item is selected? In particular, I want to get behavior similar to ShowDialog() , but for a ContextMenu .
The direct approach does not work:
ContextMenu cm = new ContextMenu(); cm.MenuItems.Add("1", (s,e) => {value = 1;}); cm.Show(control, location);
since the Click callback is not called directly from Show() , but instead at some later point in time when the message loop processes the click event.
If you're out of luck, menu is garbage collected before the event is processed, in which case the event will simply be lost. (This means that you cannot use local variables for ContextMenu in this way.)
This seems to work, but feels "unclean":
using (ContextMenu cm = new ContextMenu()) { cm.MenuItems.Add("1", (s,e) => {value = 1;}); cm.Show(control, location); Application.DoEvents(); }
Is there a better way?
source share