Search code examples
c#.net.net-core.net-5

Implement a menu on tray icon for .NET 5/6 win forms


In a .NET Framework 4.8 winform app without main form I have this code:

    [STAThread]
    public static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Daemon());
    }
    public class Daemon : ApplicationContext
    {
        private readonly NotifyIcon trayIcon;

        public Daemon()
        {
            trayIcon = new NotifyIcon()
            {
                Icon = "icon.ico",
                ContextMenu = new ContextMenu(new MenuItem[]
                { 
                    new MenuItem("OPEN", new EventHandler(Open)),
                    new MenuItem("SETTINGS", new EventHandler(Settings)),
                    new MenuItem("EXIT", new EventHandler(Exit))
                }),
                Visible = true
            };
        }
    }

In a .NET 5 (or 6) win form app, the NotifyIcon object doesn't have a ContextMenu property, but a ContextMenuStrip that I don't understand how to use.

How can I create a simple menu on a try icon for an application that doesn't have a main form?


Solution

  • It was simpler than expected.

    public Daemon()
    {
        trayIcon = new NotifyIcon()
        {
            Icon = new Icon("icon.ico"),
            ContextMenuStrip = new ContextMenuStrip(),
            Visible = true
        };
    
        trayIcon.ContextMenuStrip.Items.AddRange(new ToolStripItem[]
        {
            new ToolStripMenuItem("OPEN", null, new EventHandler(Open), "OPEN"),
            new ToolStripMenuItem("SETTINGS", null, new EventHandler(Settings), "SETTINGS"),
            new ToolStripMenuItem("EXIT", null, new EventHandler(Exit), "EXIT")
        });
    }