How to minimize to tray if it was opened on startup? C-Sharp

Viewed 64

I want to minimize my app to the tray if it was opened on start up.
But if it was opened manually it should be in taskbar

I use this code to run my app on start up

Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
key.SetValue("Your Application Name", Application.ExecutablePath);

Please don't flag this question if it was a dumb question because i'm a new to c#

2 Answers

You can add a command line parameter to the path you set in the registry key. Then check for this parameter to know if the application was auto-started.

For example, here is a sample path Steam uses:

"C:\Program Files (x86)\Steam\steam.exe" -silent

To have it minimise to tray on startup, I'd do the following:

  1. Set the registry key but add a switch on there that is explanatory e.g. /startminimised.
  2. When the program first runs, you can check arguments that have been passed to it on run using Environemnt.GetCommandLineArgs().
  3. If /startminimised is in there, simply put the program in the tray. To do that, you need to add a NotifyIcon to the WinForm first and give it a name e.g. notifyIcon.
Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
key.SetValue("Your Application Name", Application.ExecutablePath + " /startminimised");
string[] args = Environment.GetCommandLineArgs();
            
foreach(string arg in args)
{
    if (arg.Equals("/startminimised"))
    {
        Hide();
        notifyIcon.Visible = true;
    }
}
Related