NotifyIcon ContextMenu和太多的点击事件
本文关键字:事件 太多 ContextMenu NotifyIcon | 更新日期: 2023-09-27 18:11:24
我使用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;
问题是,当用户选择"功能A"或"功能B"时,我的trayIcon_IconClicked
事件被触发。为什么会这样?
谢谢,J
通过将上下文菜单分配给NotifyIcon控件,它会自动捕获右键并在那里打开分配的上下文菜单。如果你想在实际显示上下文菜单之前执行一些逻辑,那么给contextMenu分配一个委托。弹出事件。
...
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的点击处理程序。
Edit:另一个可以考虑的选择是使用ContextMenuStrip代替。NotifyIcon也有一个ContextMenuStrip属性,它似乎有更多与之相关的功能(注意到我可以做更多,可编程的)。如果由于某些原因,事情不能正常工作,可能需要尝试一下。
我遇到了同样的问题。将NotifyIcon的ContextMenu更改为ContextMenuStrip并不能解决问题(事实上,当我更改ContextMenu时,点击事件发生在ContextMenuStrip显示而不是当用户实际单击其中一个项目时)。
我对这个问题的解决方案是改变我用来显示左键上下文菜单的事件。我没有使用Click事件处理程序,而是使用MouseUp来检查哪个MouseButton被点击了。
创建NotifyIcon (notifyContext is a 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;
}
}