C# - Reading parameters/switches on run

acole1

Golden Member
Sep 28, 2005
1,543
0
0
I have a Windows Forms application that I can open and click buttons to run, but I would like to automate it's internal processes by adding a command line switch on the end so I can schedule it.

For example, executing the program with "Program.exe /autorun" would keep the program hidden, and run it's code without me opening it and clicking buttons.

Is this possible using C#?
 

Markbnj

Elite Member <br>Moderator Emeritus
Moderator
Sep 16, 2005
15,682
14
81
www.markbetz.net
I haven't done Windows Forms in awhile, but the answer is yes. You need to override a main function in your topmost class, Program or whatever, to get the arguments. Someone else here will know the specific answer, but this may be enough for you to Google your way to victory.
 

acole1

Golden Member
Sep 28, 2005
1,543
0
0
Thanks! That helped me figure it out.

I used this to do it:

public ImportNewRecord()
{
RunAtStartup();
}

private void RunAtStartup()
{
string[] args = Environment.GetCommandLineArgs();

if (args.Length > 1 && args[1].Contains("/autorun"))
{
//Do stuff
}
else
{
//Do other stuff
}
}
 
Last edited:

Cogman

Lifer
Sep 19, 2000
10,286
145
106
I don't know if C# supports this, but the native win32 API call you want is ExitProcess(0); That will terminate the program.