Link to home
Start Free TrialLog in
Avatar of silentthread2k
silentthread2kFlag for United States of America

asked on

How can I read and pass a command line argument to a C# windows form?

I don't have the args variable that I normally do with a C# console window.....

        private void Form1_Load(object sender, EventArgs e)
        {
Avatar of Carl Tawn
Carl Tawn
Flag of United Kingdom of Great Britain and Northern Ireland image

Your form doesn't receive them, but the applications Main() method can. If you make the definition of the Main() method as follows:
static void Main(string[] args)

Open in new window

You can then pass them to your form in its constructor.
ASKER CERTIFIED SOLUTION
Avatar of ViceroyFizzlebottom
ViceroyFizzlebottom
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Whoops, forgot to include example code above:

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            foreach (string args in Environment.GetCommandLineArgs())
            {
                label1.Text = args;
            }
        }
    }
I believe carl_tawn solution is good one. recently I answered a similar question:

https://www.experts-exchange.com/questions/26827599/File-association-with-my-application.html

I just want to add to carl_tawn that you may need to pass arguments to a form, i.e. your form you start from Main may need to accept arguments string:


static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1(args[0]));
        }

Open in new window

To clarify: you need to pass args to a Form's constriuctor as above. Then you can do whatever you need.

Also, just in case - the Main method is located in the class Program.
Hi,

You can use Environment.CommandLine property where ever in the code to get the program name and any arguments specified on the command line when the current process was started.
Ex: instead of using string[] args alternatively u can use this property.
class Sample
{
    public static void Main()
    {
    Console.WriteLine();
//  Invoke this sample with an arbitrary set of command line arguments.
    Console.WriteLine("CommandLine: {0}", Environment.CommandLine);
    }
}