Win32 GUI program with console output

Win32 programs have the unfortunate problem of being either GUI based or console based initially, one of the problem is that GUI programs cannot show console output by default, this shows how to re-enable console output and retrieve 'argc' and 'argv'.

This just re-enables 'stdout' and 'stderr'. We first retrieves 'argv' and 'argc'. Then if the current GUI was spawned from a console ('AttachConsole' returns true), we can re-open the 'std' handles, otherwise, no ugly console is spawned. Remember to compile in GUI mode for this to work.

After that, you can just write a regular 'main' as if you're writing a console program.

One final thought, if you don't like the fact that GUI programs return immediately after spawning, use 'start /w' command to start your program, then the CMD prompt will wait until your program exits before resuming.

#if defined(_WIN32)
// Win32 wrapper function for GUI mode
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
        LPSTR lpCmdLine, int nCmdShow){
    extern char ** __argv;
    extern int __argc;

    // This attaches a console to the parent process if it has a console
    if(AttachConsole(ATTACH_PARENT_PROCESS)){
        // reopen stout handle as console window output
        freopen("CONOUT$","wb",stdout);
        // reopen stderr handle as console window output
        freopen("CONOUT$","wb",stderr);
    }
    return main(__argc,__argv);
}
#endif

References

  1. AttachConsole on MSDN