Providing the .NET Program with the Output Type of Windows and Console Applications

I have a C # application that has gui and has its own type of output installed as a Windows application. I would also like to call it from the command line (via options), and therefore it should also be a console application. Is there a way to get my application to run both a Windows application and a console application? Is there a way to set this at runtime or is it setting compile time?

+7
windows console-application
source share
4 answers

You can attach the console. Make the code in Program.cs as follows:

[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); 
+8
source share

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

 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()); } } 
+1
source share

This is a compile-time parameter: there is a target: option target: in the csc compiler. /target:winexe creates a Windows application (i.e., with a graphical interface); /target:exe creates a console application. Both types of applications can accept command line arguments.

+1
source share

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

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

0
source share

All Articles