I'm using the NotifyIcon
class to display an icon in the task tray. The icon performs 2 functions - when the user single-clicks with the left button it should display a window, when the user single-clicks with the right button it should display the context menu. This works fine apart from the window being displayed after the user clicks an option in the context menu. Here's my code:
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;
The problem is that my trayIcon_IconClicked
event is fired when the user selects "Function A" or "Function B". Why would that be happening?
Thanks, J
By assigning the context menu to the NotifyIcon control, it automatically catches the right-click and opens the assigned context menu there. If you want to perform some logic before actually showing the context menu, then assign a delegate to the contextMenu.Popup event.
...
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.
}
My guess as to why the window is popping up is that the context menu that you're opening up is using the NotifyIcon as the target control, so when you click on it it's running the click handler you assigned to the NotifyIcon.
Edit: Another option to consider is to use ContextMenuStrip instead. The NotifyIcon has a ContextMenuStrip property as well, and it seems to have a lot more functionality associated with it (noticed I could do more, programmable wise). Might want to give that a shot if things aren't working right for some reason.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With