System tray icon with c# Console Application won't show menu

KenD picture KenD · Oct 10, 2012 · Viewed 19.5k times · Source

I've got a small C# (.NET 4.0) Console Application that I'd like the user to be able to interact by showing a menu when they right-click the System Tray icon. I can add an icon to the Tray with no problems, but I just cannot get the menu to appear. I'm using the following code:

NotifyIcon trayIcon = new NotifyIcon();
trayIcon.Text = "TestApp";
trayIcon.Icon = new Icon(SystemIcons.Application, 40, 40);

ContextMenu trayMenu = new ContextMenu();

trayMenu.MenuItems.Add("Blah", item1_Click);
trayMenu.MenuItems.Add("Blah2", item1_Click);
trayMenu.MenuItems.Add("Blah3", item1_Click);

trayIcon.ContextMenu = trayMenu;
trayIcon.Visible = true;

... which puts the icon in the tray. However, right-clicking the icon does nothing. I've tried various permutations of MenuItems.Add, but nothing will make the menu appear. I'm sure I'm missing something simple - any ideas what?

Answer

Roman Starkov picture Roman Starkov · Oct 10, 2012

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.