单击NotifyIcon上下文菜单中的ContextMenuItem会调用NotifyIcon单击事件

时间:2017-07-26 20:37:46

标签: c# winforms contextmenu notifyicon

我有一个只在托盘中启动的WinForms应用程序。单击它,它会打开一个表单。这很好。

    notifyIcon.Click += notifyIcon_Click;

//Fires on icon click, AND on contextmenuitem click
    private void notifyIcon_Click(object sender, EventArgs e)
            {
                new ActiveIssues(_hubProxy).Show();
            }

我添加了一个上下文菜单,但是当我单击ContextMenuItem时,它首先触发NotifyIcon click事件,然后触发ContextMenuItem click事件,打开两个表单。

    notifyIcon.ContextMenu = GetCrestContextMenu();

     private ContextMenu GetCrestContextMenu()
            {
                var contextMenu = new ContextMenu();
                contextMenu.Name = "CResT Alerts";
                contextMenu.MenuItems.Add(GetTextOptionMenuItem());
                return contextMenu;
            }

            private MenuItem GetTextOptionMenuItem()
            {
                var textOptionMenuItem = new MenuItem { Text = _textOptedIn ? "Opt Out of Text Alerts" : "Opt In to Text Alerts" };
                textOptionMenuItem.Click += TextOptionMenuItem_Click;
                return textOptionMenuItem;
            }

//Fires on menuitem click, after the NotifyIcon click event is called
            private void TextOptionMenuItem_Click(object sender, EventArgs e)
            {
                if (_textOptedIn) new TextOptOut().Show();
                else new TextOptIn().Show();
            }

知道如何不让它触发notifiyicon点击事件或告诉点击是否在上下文菜单上?

1 个答案:

答案 0 :(得分:2)

事实证明,直到单击上下文菜单后才会注册右键单击,因此右键单击注册并引发了NotifyIcon单击事件。因此,我不得不将为ClickA提供的EventArgs转换为MouseEventArgs,并检查按钮。

private void notifyIcon_Click(object sender, EventArgs e)
    {
        if(((MouseEventArgs)e).Button == MouseButtons.Left) new ActiveIssues(_hubProxy).Show();
    }