C++ – Win32 Console application that can open windows

cwinapiwindows

My question is pretty simple. In Ubuntu, programs can often be deployed with or without a GUI, perhaps using a flag like –showGUI. I essentially want to recreate this functionality in windows, but it seems that windows applications start with win_main, while console applications start with main.

So what is the basic structure required to produce this behavior? E.g. in in Visual Studio 2012, should I start with a Windows App and then hide the window and write to console? Or can I start with an empty Console Application and create a window with the windows API?

Thanks

(c/c++, btw)

Best Answer

A console application starts out attached to a console. It can then create windows as it sees fit--essentially no different from an application written specifically for the windows subsystem.

In theory you can do the opposite: create an application for the windows subsystem, and then attach a console to it. This adds a fair amount of extra work though. The startup code in the standard library normally does some work to attach stdin/cin, stdout/cout, stderr/cerr to the console. If you create a windows subsystem program, then attach a console, you basically have to reproduce that code to attach the console to the standard streams.

As such, it's usually easiest to start with a program written for the console subsystem and have it create windows than start with a program written for the windows subsystem and have it create/attach a console.

As far as main vs. WinMain goes: this controls which subsystem the program will be linked for by default. That is, if you have a function named main, it'll default to the console subsystem. If you have a function named WinMain, it'll default to the windows subsystem (offhand I don't remember which it'll do if you define both--I'd advise against doing that).

You can, however, force the subsystem choice with a linker flag if you want to, so you can use main as the entry point for a windows-subsystem program, or WinMain as the entry point for a console-subsystem program. I'd generally advise against doing either of those as well though.