有没有一种方法来显示"堵"的WinForms文本菜单?方法来、菜单、文本、WinForms

2023-09-05 01:16:15 作者:今天过后、再无关联

有没有一种方法来显示文本菜单并阻止进一步执行,直到项目已被选中?我特别想获得类似的行为的ShowDialog()但对于文本菜单

Is there a way to show a ContextMenu and block further execution until an item has been selected? In particular, I want to get behavior similar to ShowDialog() but for a ContextMenu.

在直接的方法行不通:

ContextMenu cm = new ContextMenu();
cm.MenuItems.Add("1", (s,e) => {value = 1;});
cm.Show(control, location);

因为点击回调是直接从不叫展(),而是在以后某个时候,消息循环处理click事件。

since the Click callback isn't called directly from Show() but instead at some later point when the message loop processes the click event.

如果你运气不好,菜单是垃圾事件之前收集的处理,在这种情况下,该事件只是默默的消失。 (意思是这样,你真的不能使用局部变量文本菜单秒)

If you are unlucky, menu is garbage collected before the event is processed and in that case the event is just silently lost. (Meaning you can't really use local variables for ContextMenus 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?

推荐答案

只是等待的菜单不visiable。

Just wait for the menu to not be visiable.

ContextMenu cm = new ContextMenu();
cm.MenuItems.Add("1", (s,e) => {value = 1;});
cm.Show(control, location);
while (cm.Visible == true) Application.DoEvents();