Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Giving .NET program an output type of windows application and console application

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 as a Console Application?
Is there a way to set this at run time or is it a compile time setting?

like image 803
DanDan Avatar asked Sep 06 '10 14:09

DanDan


2 Answers

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);
like image 103
Hans Passant Avatar answered Sep 22 '22 04:09

Hans Passant


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());
    }
}
like image 22
João Angelo Avatar answered Sep 24 '22 04:09

João Angelo