System tray icon with c# Console Application won't show menu
Try adding this after you create the icon:
Application.Run()
Note that this method will not return, so you can't do anything after calling it. This means that you'll have to do all your other work in a separate thread.
What happens is that the OS sends your application a message telling it that the tray icon has been right-clicked, but the tray icon code never sees it (because these messages are processed by Application.Run
) and so can't respond by opening the menu.
Concerning Application.Run()
, this is an alternative to placing all the other code in another thread would be to create the NotifyIcon
, menu
, events
, etc on a thread other than the main thread.
This should include Application.Run()
as this allows the standard application message loop to work on the current thread. Then since the events were created on the same thread, the Application.Exit()
can be used to close out the notification messaging but still allow the main thread to continue. Here's a small example for a console app...
class Program
{
public static ContextMenu menu;
public static MenuItem mnuExit;
public static NotifyIcon notificationIcon;
static void Main(string[] args)
{
Thread notifyThread = new Thread(
delegate()
{
menu = new ContextMenu();
mnuExit = new MenuItem("Exit");
menu.MenuItems.Add(0, mnuExit);
notificationIcon = new NotifyIcon()
{
Icon = Properties.Resources.Services,
ContextMenu = menu,
Text = "Main"
};
mnuExit.Click += new EventHandler(mnuExit_Click);
notificationIcon.Visible = true;
Application.Run();
}
);
notifyThread.Start();
Console.ReadLine();
}
static void mnuExit_Click(object sender, EventArgs e)
{
notificationIcon.Dispose();
Application.Exit();
}
}