Nayrb
Nayrb

Reputation: 1043

Having a System tray in a Console Application with a menu in C#

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);
    }
  }
}

Upvotes: 1

Views: 2552

Answers (1)

4D1C70
4D1C70

Reputation: 490

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.

Upvotes: 1

Related Questions