Getting the command line arguments in a GUI Program using C#
by
on 02-14-2009 at 11:01 AM (2328 Views)
Getting the command line arguments in a GUI Program using C#
In this short tutorial I will explain to you how you can get arguments in a GUI application using C#. So let’s say that you have a program that you want that during start up it stays in the background and when the user opens it, it will display the normal GUI. It’s very simple; we will only need to make a few changes to the program.
So, open up Program.cs (find it from the Solution Explorer) you will see something like
Change that toCode:[STAThread] static void Main()
The string[] args will get the parameters and store them into a string array, so if you will make something likeCode:[STAThread] static void Main(string[] args)
You will have 3 parameters (because they are separated with a space), meaning your string array will have three parameters.myexe.exe first second third
Now all you have to do is make a form constructor that will accept a string array, by making something like
Replace Form1 with your main form name and it will accept the array, don’t forget to make the : this() part because if you don’t it won’t execute the default constructor.Code:public Form1(string[] commands) : this() { }
Go back to the program.cs and find something like Application.Run(new Form1()); and replace that with the following code
So if you will execute with no arguments it will load the default constructor and will load as normal, but if you will have some arguments it will load the other constructor and forward to the new form. Now go back to the new constructor and just make some code to do whatever you need to do, you can read the first argument and if that has a string that says ‘background’ it will run with the form as hidden (so it will run in the background). All you need to do is just loop through the array, make a couple of if statements and you are doneCode:if(args.Length != 0) Application.Run(new Form1(args)); else Application.Run(new Form1());
In a console application you will already have the main that accepts the arguments, all you will have to do is just loop through them or whatever.
Hope this was helpful.










