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?
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.
Finally to test the Startup argument outside of visual studio add the startup argument to your shortcut, such as the screenshot below.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With