See this post from Raymond Chen: How do I write a program that can be run as a console or GUI application?
Excerpts:
You cannot, but you can try to fake it.
[...]
There are some people who want to write what I call the “opportunistic” console program. These are programs that will use their parent's console if they are available, but do not want the console to be created for them if not. The kernel does not support this type of program, but this did not stop some people from using smart workarounds .
The problem is that the solution is "to connect to an existing console window for input and output or run as a console application with a graphical interface"? occurs before the start of the process. You cannot write code that makes this decision based on command line options.
Windows forces you to make a decision at compile time: this application will use the console (in this case it always has a console window and opens a new one if it was launched from the icon or the Start menu)), or it will not use the console (in in this case, he cannot direct input or output to the console window from which he was launched - he can, however, create a new console window ). If you want to always have a console, change the assembly type to "Console application"; if you do not want to have a console, leave it as a “Windows application”.
The smart workarounds cited in the Raymond post, in case of link decay, are devenv (Visual Studio) and ildasm:
In the case of VisualStudio, there are actually two binaries: devenv.com and devenv.exe. Devenv.com is a console application. Devenv.exe is a graphical application. When you enter devenv, due to the Win32 validation rule, devenv.com is executed. If there is no entry, devenv.com launches the devenv.exe file and exits it. If there are inputs, devenv.com treats them like a regular console application.
In the case of ildasm, there is only one binary file: ildasm.exe. It is first compiled as a GUI application. Later, editbin.exe is used to mark it as a console subsystem. In his main method, he determines whether to run it in console or graphical interface mode. If you need to run in GUI mode, it will resume working with the graphical interface.