NotifyIcon ContextMenu和太多的点击事件

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

 contextMenuItems = new List(); 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; 

问题是当用户选择“functionA”或“functionB”时会触发我的trayIcon_IconClicked事件。 为什么会这样?

谢谢,J

通过将上下文菜单分配给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. } 

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

编辑:要考虑的另一个选择是使用ContextMenuStrip。 NotifyIcon也有一个ContextMenuStrip属性,它似乎有更多与之相关的function(注意我可以做更多,可编程)。 如果某些事情由于某种原因不能正常工作,可能想要给出一个机会。

我遇到了同样的问题。 将NotifyIcon的ContextMenu更改为ContextMenuStrip并没有解决问题(实际上当我更改了ContextMenu时,当ContextMenuStrip显示而不是当用户实际点击其中一个项目时,会发生Click事件。

我对此问题的解决方案是更改用于显示左键单击上下文菜单的事件。 我没有使用Click事件处理程序,而是使用MouseUp并检查单击了哪个MouseButton。

构建NotifyIcon(notifyContext是一个System.Windows.Forms.ContextMenuStrip)

 m_notifyIcon.MouseUp += new Forms.MouseEventHandler(m_notifyIcon_MouseUp); m_notifyIcon.ContextMenuStrip = notifyContext; Handling the left click event and show the main contextmenu: void m_notifyIcon_MouseUp(object sender, Forms.MouseEventArgs e) { if (e.Button == Forms.MouseButtons.Left) { mainContext.IsOpen = ! mainContext.IsOpen; } }