Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect an application runs by user click or Windows startup in C#

Tags:

c#

winforms

I've a C# WinForm application. Currently it runs from a desktop shortcut. But I would like to add it in system startup. User can decide whether it will run on startup or not.

If it runs on system startup, I would like to minimize it on system tray, otherwise it will run on task-bar.

Is there any way to check whether it is being launched on startup or not?

like image 542
s.k.paul Avatar asked May 05 '15 04:05

s.k.paul


2 Answers

Your application wont be able to detect (by itself) it was launched at startup or by normal user launching. However you can pass arguments to your application and then have your application respond correctly. Here is a basic example

First start in program.cs main method. Now by default you dont see the startup arguments passed in. However adding the parameter string[] args to the main() method will expose the command arguments. Such as

static class Program
{
    public static bool LaunchedViaStartup { get; set; }

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main(string[] args)
    {
        Program.LaunchedViaStartup = args != null && args.Any(arg => arg.Equals("startup", StringComparison.CurrentCultureIgnoreCase));

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }
}

Now the code is simple, we set a static variable to the Program class called LaunchedViaStartup then before the program starts our main form we check if the command arguments contains our special startup argument (via Linq). The name for this argument is simply up to you.

Now in our main form (yes basic) we have access to this property for the lifetime of the application.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        MessageBox.Show(this, string.Format("Lanched Via Startup Arg:{0}", Program.LaunchedViaStartup));
    }
}

Finally to test this you can simple open the Project Properties window and set the Command line arguments similar to the screenshot below.

enter image description here

Finally to test the Startup argument outside of visual studio add the startup argument to your shortcut, such as the screenshot below.

enter image description here

like image 117
Nico Avatar answered Nov 06 '22 09:11

Nico


Send commend line arguments when you run from start up (define it in shortcut path).

Get the arguments in your application main and take decision based on the arguments. Now, It's up to you how you achieve it.

Check MSDN

Here it is for WinForm

like image 26
Shaharyar Avatar answered Nov 06 '22 11:11

Shaharyar