views:

52

answers:

4

I have a C# application that has a gui and has its output type set as Windows application. I would also like to invoke it from the command line (via parameters) and thus it needs to also be a console application. Is there a way to get my application to run both as a windows application and a console application? Is there a way to set this at run time or is it a compile time setting?

+1  A: 

A Windows Forms application can accept command line arguments. You just need to handle this case in your main function before showing the application Main form.

static void Main(string[] args)
{
    if (args.Length > 0)
    {
        // Run it without Windows Forms GUI
    }
    else
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new MainForm());
    }
}
João Angelo
A: 

Even your applications output type is set as Windows application, you can still invoke it from the command line and pass arguments.

Just change your Main method definition to : static void Main(string[] args) {...} and you have access to passed arguments in 'args' variable.

Bartłomiej Mucha
+1  A: 

It's a compile-time setting: there's a target: option on the csc compiler. /target:winexe builds a Windows application (i.e. with a GUI); /target:exe builds a console application. Both types of application can accept command line arguments, though.

Graham Clark
I've ended up building both - I wanted a true windows program and a true console application.
DanDan
+4  A: 

You can attach the console. Make the code in Program.cs look like this:

    [STAThread]
    static void Main(string[] args) {
        if (args.Length > 0) {
            AttachConsole(-1);
            Console.WriteLine("");
            Console.WriteLine("Running in console, press ENTER to continue");
            Console.ReadLine();
        }
        else {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
    [System.Runtime.InteropServices.DllImport("kernel32.dll")]
    private static extern bool AttachConsole(int pid);
Hans Passant
This kind of works but it seems a bit quirky. I will accept but I've gone for two separate applications, Windows and Console.
DanDan
The quirky bit is probably you writing in a console you didn't create. Output gets mixed. You can also use AllocConsole() but then it gets its own.
Hans Passant