126

I have two different WinForms applications, AppA & AppB. Both are running .NET 2.0.

In AppA I want to open AppB, but I need to pass command-line arguments to it. How do I consume the arguments that I pass in the command line?

This is my current main method in AppB, but I don't think you can change this?

  static void main()
  {
  }

6 Answers 6

233

The best way to work with args for your winforms app is to use

string[] args = Environment.GetCommandLineArgs();

You can probably couple this with the use of an enum to solidify the use of the array througout your code base.

"And you can use this anywhere in your application, you aren’t just restricted to using it in the main() method like in a console application."

Found at:HERE

6
  • 27
    The first element in the array contains the file name of the executing program. If the file name is not available, the first element is equal to String.Empty. The remaining elements contain any additional tokens entered on the command line.
    – EKanadily
    Apr 2, 2014 at 7:15
  • @docesam That helped me a lot, thanks! Was wondering why it kept trying to load the program itself as text.
    – Kaitlyn
    Aug 29, 2015 at 5:01
  • 1
    On MSDN: Environment.GetCommandLineArgs Method ()
    – DavidRR
    Nov 22, 2016 at 15:49
  • After years of C# development i never knew this method existed. Nice.
    – CathalMF
    May 25, 2018 at 16:41
  • 1
    is there a benefit to using this method vs sending the parameters main(string[] args)?
    – Adjit
    Jun 14, 2018 at 14:09
130
static void Main(string[] args)
{
  // For the sake of this example, we're just printing the arguments to the console.
  for (int i = 0; i < args.Length; i++) {
    Console.WriteLine("args[{0}] == {1}", i, args[i]);
  }
}

The arguments will then be stored in the args string array:

$ AppB.exe firstArg secondArg thirdArg
args[0] == firstArg
args[1] == secondArg
args[2] == thirdArg
5
  • 6
    input: "whatever.exe -v foo /lol nisp". Output: args[0] = "-v"; args[1] = "foo"; args[2] = "/lol"; args[3] = "nisp"; What could be easier? Jul 24, 2009 at 19:22
  • cant believe i saw that 'string[] args' so many times after a whole year and it never occured to me wtf it was untill now ! haha
    – Niklas
    Jun 28, 2016 at 18:31
  • 2
    It seems that args[0] is the full path and exe name of the application running and args[1] is the first parameter.
    – Allan F
    Apr 21, 2020 at 0:09
  • The question is about WinForms applications -- which have no Console and user functionality needs to run from the main form. Nov 2, 2022 at 10:09
  • @ivan_pozdeev Console is just for the example of course, as commented in the code.
    – Thomas
    Nov 2, 2022 at 12:50
17

Consider you need to develop a program through which you need to pass two arguments. First of all, you need to open Program.cs class and add arguments in the Main method as like below and pass these arguments to the constructor of the Windows form.

static class Program
{    
   [STAThread]
   static void Main(string[] args)
   {            
       Application.EnableVisualStyles();
       Application.SetCompatibleTextRenderingDefault(false);
       Application.Run(new Form1(args[0], Convert.ToInt32(args[1])));           
   }
}

In windows form class, add a parameterized constructor which accepts the input values from Program class as like below.

public Form1(string s, int i)
{
    if (s != null && i > 0)
       MessageBox.Show(s + " " + i);
}

To test this, you can open command prompt and go to the location where this exe is placed. Give the file name then parmeter1 parameter2. For example, see below

C:\MyApplication>Yourexename p10 5

From the C# code above, it will prompt a Messagebox with value p10 5.

0
12

You can grab the command line of any .Net application by accessing the Environment.CommandLine property. It will have the command line as a single string but parsing out the data you are looking for shouldn't be terribly difficult.

Having an empty Main method will not affect this property or the ability of another program to add a command line parameter.

1
  • 26
    Or use Environment.GetCommandLineArgs() which returns an string array of arguments just like Main(string[] args)
    – Brettski
    Jun 11, 2010 at 3:49
7

You use this signature: (in c#) static void Main(string[] args)

This article may help to explain the role of the main function in programming as well: http://en.wikipedia.org/wiki/Main_function_(programming)

Here is a little example for you:

class Program
{
    static void Main(string[] args)
    {
        bool doSomething = false;

        if (args.Length > 0 && args[0].Equals("doSomething"))
            doSomething = true;

        if (doSomething) Console.WriteLine("Commandline parameter called");
    }
}
4

This may not be a popular solution for everyone, but I like the Application Framework in Visual Basic, even when using C#.

Add a reference to Microsoft.VisualBasic

Create a class called WindowsFormsApplication

public class WindowsFormsApplication : WindowsFormsApplicationBase
{

    /// <summary>
    /// Runs the specified mainForm in this application context.
    /// </summary>
    /// <param name="mainForm">Form that is run.</param>
    public virtual void Run(Form mainForm)
    {
        // set up the main form.
        this.MainForm = mainForm;

        // Example code
        ((Form1)mainForm).FileName = this.CommandLineArgs[0];

        // then, run the the main form.
        this.Run(this.CommandLineArgs);
    }

    /// <summary>
    /// Runs this.MainForm in this application context. Converts the command
    /// line arguments correctly for the base this.Run method.
    /// </summary>
    /// <param name="commandLineArgs">Command line collection.</param>
    private void Run(ReadOnlyCollection<string> commandLineArgs)
    {
        // convert the Collection<string> to string[], so that it can be used
        // in the Run method.
        ArrayList list = new ArrayList(commandLineArgs);
        string[] commandLine = (string[])list.ToArray(typeof(string));
        this.Run(commandLine);
    }

}

Modify your Main() routine to look like this

static class Program
{

    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        var application = new WindowsFormsApplication();
        application.Run(new Form1());
    }
}

This method offers some additional usefull features (like SplashScreen support and some usefull events)

public event NetworkAvailableEventHandler NetworkAvailabilityChanged;d.
public event ShutdownEventHandler Shutdown;
public event StartupEventHandler Startup;
public event StartupNextInstanceEventHandler StartupNextInstance;
public event UnhandledExceptionEventHandler UnhandledException;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.