How to make an application as both GUI and Console application?

This is another common asked question. But it is a Win32 question.

In Windows GUI applications and Console applications are very different. GUI applications have at least one window, and a message loop, but no standard in/out/error. Console applications have standard in/out/error, but no window, no message loop. An application is either a GUI application or Console application, but not both.

Some people want their application behaves differently depending on input. If there are inputs, the application behaves like Console application. If there is no input, it behaves like GUI applications.

Just like devenv (Visual Studio) and ildasm.

How do they do that?

VisualStudio and ildasm achieve this very differently.

In VisualStudio case, there are actually two binaries: devenv.com and devenv.exe. Devenv.com is a Console app. Devenv.exe is a GUI app. When you type devenv, because of the Win32 probing rule, devenv.com is executed. If there is no input, devenv.com launches devenv.exe, and exits itself. If there are inputs, devenv.com handles them as normal Console app.

In ildasm case, there is only one binary: ildasm.exe. It is first compiled as a GUI application. Later editbin.exe is used to mark it as console subsystem. In its main method it determines if it needs to be run as console mode or GUI mode. If need to run as GUI mode, it relaunches itself as a GUI app.