0

I've scoured this site and numerous other resources for trying to track this down.

I have a console application that I am trying to get have a system tray icon for.

That part works.

What I cannot actually get to work is adding a menu to it when I right click. I really just need an exit button that will shut it down.

My entire class is fairly small so I will include it. I have initialized this object in my main method and thats pretty much all I need since I drive this from the constructor. I've found resource that indicated I would not need a click event but I've tried both so Im not exactly sure.

I've tried patching this together from other resources but everyone seems to have a slightly different problem or I'm missing something.

Thanks for taking a look.

namespace PvsMessageLogger
{
  public class SystemTray
  {
    private readonly string _systemDisplayName;
    private readonly NotifyIcon _systemTray;
    public SystemTray(string systemDisplayName)
    {
      _systemTray = new NotifyIcon();
      _systemDisplayName = systemDisplayName;
      InitializeSystemTray();
    }

    private void InitializeSystemTray()
    {
      _systemTray.Icon = new Icon(SystemIcons.Application, 40, 40);
      _systemTray.Visible = true;
      _systemTray.BalloonTipTitle = _systemDisplayName;
      _systemTray.BalloonTipText = _systemDisplayName + " is running in the background";
      MenuItem[] menuList = {new MenuItem("Exit", (s, e) => Application.Exit()) };

      ContextMenu clickMenu = new ContextMenu(menuList);
      _systemTray.ContextMenu = clickMenu;
      _systemTray.ShowBalloonTip(1000);
    }
  }
}
Bryan Harrington
  • 991
  • 2
  • 17
  • 31
  • See [this answer](https://stackoverflow.com/questions/12817468/system-tray-icon-with-c-sharp-console-application-wont-show-menu) – CodingYoshi Sep 12 '17 at 17:34
  • 2
    A fundamental requirement for NotifyIcon is running a message loop. It is the only way that the OS can deliver notifications. You could start another thread and have it call Application.Run(). – Hans Passant Sep 12 '17 at 17:39
  • @HansPassant why start another thread? – CodingYoshi Sep 12 '17 at 17:56
  • Anybody that tries it will discover why. Call Application.Run() on the main thread and it is just not a console app anymore. You might as well start with the Winforms template and change the Output type setting to "Console", that's better. – Hans Passant Sep 12 '17 at 18:02

1 Answers1

1

Just found the answer in another thread, you must add Application.Run() after you create the icon.

You can find more details on Roman's answer.

4D1C70
  • 490
  • 3
  • 10