Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

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, which start and run in the system tray silently.

I want the same effect and when user click the "show" button of the notifyIcon's contextmenustrip then only application should show GUI.

I'm using this, but its not working

    private void Form_Load(object sender, EventArgs e)
    {
        this.Hide();
    }

May be I need to have Main() function in some other class which has no GUI but has notifyIcon & ContextMenuStrip whose option will instantiate the GUI window class. Right?

like image 541
claws Avatar asked Oct 24 '09 11:10

claws


People also ask

How do I run an application in my system tray?

Run the program from its folder or from a shortcut you've created. Switch to whichever window you'd like to minimize to the tray. Press Alt + F1 and that window will minimize to the tray.

What is tray application?

The Windows System Tray Application provides a self-service tool for the end user. The end user clicks the System Tray Application icon and then selects an action from the menu. You can Enable or Edit the System Tray Application to match your requirements.

What is the system tray on my computer?

The system tray (or "systray") is a section of the taskbars in the Microsoft Windows operating system (OS) user interface that provides easy access icons to the user's most commonly used apps and displays the clock. A system tray is also available in other OSes such as Linux, Mac OS, Android and iOS.


1 Answers

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.

like image 198
Matthew Scharley Avatar answered Sep 20 '22 07:09

Matthew Scharley