12

I would like a Windows Forms application that will contain a UI, but I want it to run from the command line with some parameters, possibly also a /hide or /visible=false option.

How is it possible to read in the command line parameters? And adjust accordingly?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
JL.
  • 78,954
  • 126
  • 311
  • 459

4 Answers4

27

If you change this default Main signature:

[STAThread]
static void Main()

To this:

[STAThread]
static void Main(String[] args)

You can access the commandline variables as you would from a normal console app, or if you want to access them from elsewhere you can use:

System.Environment.GetCommandLineArgs();
Steven Robbins
  • 26,441
  • 7
  • 76
  • 90
  • Hah, that first method is what I used in an explanation to a friend a while back. +1 – Kawa Oct 05 '09 at 18:36
8
[STAThread]
static void Main(string[] args)
{
    if (args.Length == 0)
    {
        // Run the application in a windows form
        Application.Run(new MainForm( ));
    }
    else
    {
        // Run app from CLI
        Console.WriteLine(DoStuff(args));
    }
}
Dour High Arch
  • 21,513
  • 29
  • 75
  • 90
  • 1
    +1 for answering the second part of the question. You are missing a bracket at the end of WriteLine(. Also, I don't think you can write to the console like that in a windows form application. – Randy Levy Oct 05 '09 at 18:49
  • You are right that you cannot Console.WriteLine to a Winforms app. The point of my answer is that you need not create a Windforms app, you can create a single executable that will run as a form or command-line depending on how it is invoked. – Dour High Arch Oct 05 '09 at 18:56
  • I just tested this and there is no commandwindow open for the text, I think it's missing a command to startup the comamndline window. – Eric Brown - Cal Apr 29 '11 at 21:06
  • @Eric, good catch; an example that connects to StdOut is [here](http://stackoverflow.com/a/1040730/22437). `Console.WriteLine` was probably a bad example for such a short snippet. – Dour High Arch Mar 18 '13 at 16:22
3

Use Environment.GetCommandLineArgs()

Kobi
  • 135,331
  • 41
  • 252
  • 292
2

Yes, it should work to create the project as a normal windows app project. Then in program.cs before you launch the window, call Environment.GetCommandLineArgs() to get the command line arguments and parse them to do what you want.

David
  • 34,223
  • 3
  • 62
  • 80