NotifyIcon ContextMenu 和太多的点击事件

JWo*_*ood 5 .net c# wcf winforms

我正在使用NotifyIcon该类在任务托盘中显示一个图标。该图标执行 2 个功能 - 当用户单击左键时应显示一个窗口,当用户单击右键时应显示上下文菜单。除了在用户单击上下文菜单中的选项后显示的窗口之外,这可以正常工作。这是我的代码:

contextMenuItems = new List<MenuItem>();
contextMenuItems.Add(new MenuItem("Function A", new EventHandler(a_Clicked)));
contextMenuItems.Add(new MenuItem("-"));
contextMenuItems.Add(new MenuItem("Function B", new EventHandler(b_Clicked)));
trayIcon = new System.Windows.Forms.NotifyIcon();
trayIcon.MouseClick += new MouseEventHandler(trayIcon_IconClicked);
trayIcon.Icon = new Icon(GetType(), "Icon.ico");
trayIcon.ContextMenu = contextMenu;
trayIcon.Visible = true;
Run Code Online (Sandbox Code Playgroud)

问题是trayIcon_IconClicked当用户选择“功能 A”或“功能 B”时会触发我的事件。为什么会发生这种情况?

谢谢,J

SPF*_*ake 3

通过将上下文菜单分配给 NotifyIcon 控件,它会自动捕获右键单击并打开分配的上下文菜单。如果您想在实际显示上下文菜单之前执行一些逻辑,请将委托分配给 contextMenu.Popup 事件。

...
contextMenu.Popup += new EventHandler(contextMenu_Popup);
...

private void trayIcon_IconClicked(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        //Do something here.
    }
    /* Only do this if you're not setting the trayIcon.ContextMenu property, 
    otherwise use the contextMenu.Popup event.
    else if(e.Button == MouseButtons.Right)
    {
        //Show uses assigned controls Client location to set position, 
        //so must go from screen to client coords.
        contextMenu.Show(this, this.PointToClient(Cursor.Position));
    }
    */
}

private void contextMenu_Popup(object sender, EventArgs e)
{
    //Do something before showing the context menu.
}
Run Code Online (Sandbox Code Playgroud)

我对弹出窗口的猜测是,您打开的上下文菜单使用 NotifyIcon 作为目标控件,因此当您单击它时,它会运行您分配给 NotifyIcon 的单击处理程序。

编辑:要考虑的另一个选择是使用 ContextMenuStrip 代替。NotifyIcon 也有一个 ContextMenuStrip 属性,并且它似乎有更多与之相关的功能(注意到我可以做更多,可编程明智)。如果由于某种原因事情不正常,可能会想尝试一下。