在项目可见时添加项目时,阻止ContextMenu进行消隐

时间:2011-11-07 00:57:36

标签: c# winforms contextmenu

似乎如果你在ContextMenu打开时添加一个条目,它就会变成一个空白的小方块。

像这样:

要重现,只需创建一个新的WinForms应用程序并将Form1类替换为:

public partial class Form1 : Form
{
    ContextMenu _menu = new ContextMenu();

    public Form1()
    {
        InitializeComponent();

        ContextMenu = _menu;

        _menu.MenuItems.Add(new MenuItem() { Text = "Test" });

        Timer a = new Timer() { Interval = 3000 };
        a.Tick += (sender, e) =>
        {
            _menu.MenuItems.Add(new MenuItem() { Text = "Woah!" });
        };
        a.Start();
    }
}

然后只需启动,右键单击并等待。

是否可以解决这个问题,而无需使用像ContextMenuStrip这样的东西?

1 个答案:

答案 0 :(得分:2)

添加后立即使用Show方法解决问题:

Timer a = new Timer() { Interval = 3000 };
a.Tick += (sender, e) =>
{
    _menu.MenuItems.Add(new MenuItem() { Text = "Woah!" });
    _menu.Show(this, Point.Empty);
};

您可能还需要跟踪弹出状态以避免意外显示。以下是实现这一目标的完整资源:

public partial class Form1 : Form
{
    ContextMenu _menu = new ContextMenu();

    public Form1()
    {
        InitializeComponent();

        ContextMenu = _menu;

        _menu.Popup += new EventHandler(_menu_Popup);
        _menu.Collapse += new EventHandler(_menu_Collapse);

        _menu.MenuItems.Add(new MenuItem() { Text = "Test" });

        Timer a = new Timer() { Interval = 3000 };
        a.Tick += (sender, e) =>
        {
            _menu.MenuItems.Add(new MenuItem() { Text = "Woah!" });
            if (_menuPoppedUp)
                _menu.Show(this, Point.Empty);
        };
        a.Start();
    }

    bool _menuPoppedUp;

    void _menu_Collapse(object sender, EventArgs e)
    {
        _menuPoppedUp = false;
    }

    void _menu_Popup(object sender, EventArgs e)
    {
        _menuPoppedUp = true;
    }
}