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()
  {
  }
Shuft
  • 1,400
  • 2
  • 11
  • 11
MRFerocius
  • 5,509
  • 7
  • 39
  • 47

6 Answers6

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

Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
Hannibul33
  • 2,431
  • 1
  • 13
  • 4
  • 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 02 '14 at 07:15
  • @docesam That helped me a lot, thanks! Was wondering why it kept trying to load the program itself as text. – Kaitlyn Aug 29 '15 at 05:01
  • 1
    On MSDN: [Environment.GetCommandLineArgs Method ()](https://msdn.microsoft.com/en-us/library/system.environment.getcommandlineargs(v=vs.110).aspx) – DavidRR Nov 22 '16 at 15:49
  • After years of C# development i never knew this method existed. Nice. – CathalMF May 25 '18 at 16:41
  • 1
    is there a benefit to using this method vs sending the parameters `main(string[] args)`? – Adjit Jun 14 '18 at 14:09
  • Environment.GetCommandLineArgs(); is useful to get the args later on if you don't want to pass them around or save them in your program. Going the route of 'Main(string[] args){' is still valid and works. – Delta Nov 13 '22 at 11:00
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
Thomas
  • 174,939
  • 50
  • 355
  • 478
  • 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? – Callum Rogers Jul 24 '09 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 '16 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 '20 at 00:09
  • The question is about WinForms applications -- which have no `Console` and user functionality needs to run from the main form. – ivan_pozdeev Nov 02 '22 at 10:09
  • @ivan_pozdeev `Console` is just for the example of course, as commented in the code. – Thomas Nov 02 '22 at 12:50
16

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.

Sarath Subramanian
  • 20,027
  • 11
  • 82
  • 86
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.

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • 26
    Or use Environment.GetCommandLineArgs() which returns an string array of arguments just like Main(string[] args) – Brettski Jun 11 '10 at 03: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");
    }
}
KreepN
  • 8,528
  • 1
  • 40
  • 58
chrisghardwick
  • 323
  • 1
  • 5
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;
Jürgen Steinblock
  • 30,746
  • 24
  • 119
  • 189