How to start the application directly in system tray? (.NET C#)

后端 未结 3 521
终归单人心
终归单人心 2021-01-04 18:19

I mean when the user starts my application(exe). I want it to start directly in system tray, without showing the window. Like antivirus softwares & download managers, wh

3条回答
  •  半阙折子戏
    2021-01-04 19:05

    The way I usually setup something like this is to modify the Program.cs to look something like the following:

        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
    
            using (NotifyIcon icon = new NotifyIcon())
            {
                icon.Icon = System.Drawing.Icon.ExtractAssociatedIcon(Application.ExecutablePath);
                icon.ContextMenu = new ContextMenu(new MenuItem[] {
                    new MenuItem("Show form", (s, e) => {new Form1().Show();}),
                    new MenuItem("Exit", (s, e) => { Application.Exit(); }),
                });
                icon.Visible = true;
    
                Application.Run();
                icon.Visible = false;
            }
        }
    

    Using this, you don't need to worry about hiding instead of closing forms and all the rest of the hacks that can lead to... You can make a singleton form too instead of instantiating a new Form every time you click the show form option. This is something to build off of, not the end solution.

提交回复
热议问题