View RSS Feed

TcM

Getting the command line arguments in a GUI Program using C#

Rate this Entry
by
TcM
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
Code:
[STAThread]
static void Main()
Change that to
Code:
[STAThread]
static void Main(string[] args)
The string[] args will get the parameters and store them into a string array, so if you will make something like
myexe.exe first second third
You will have 3 parameters (because they are separated with a space), meaning your string array will have three parameters.
Now all you have to do is make a form constructor that will accept a string array, by making something like
Code:
 public Form1(string[] commands) : this()
        {
        }
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.
Go back to the program.cs and find something like Application.Run(new Form1()); and replace that with the following code
Code:
if(args.Length != 0)
            Application.Run(new Form1(args));
            else
            Application.Run(new Form1());
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 done
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.

Submit "Getting the command line arguments in a GUI Program using C#" to Digg Submit "Getting the command line arguments in a GUI Program using C#" to del.icio.us Submit "Getting the command line arguments in a GUI Program using C#" to StumbleUpon Submit "Getting the command line arguments in a GUI Program using C#" to Google

Tags: None Add / Edit Tags
Categories
Uncategorized

Comments

  1. Jordan -
    Jordan's Avatar
    Nice Tutorial, TcM. I would +rep you but I can't in here.
    • |
    • permalink

Trackbacks

Total Trackbacks 0
Trackback URL: