'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 1:[1]

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

Solution 2:[2]

Same as the accepted answer but slightly more concise, for better or worse:

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

If that Items = {...} syntax seems strange, see here.

Also, here is a table showing the Windows Forms classes that were removed in .NET Core 3 and their corresponding replacements.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nodiink
Solution 2