Creating a console from a windows subsystem program

Sometimes, printing messages and dumping variables can be very handy for debugging purposes, but most of today’s programs do not need and in fact do not open a console window.

The following is a way a console can be opened from a windows subsystem application.

// Open the console window
AllocConsole();

// Assign the stdin/stdout/stderr streams to the newly created console
_tfreopen_s(&fpStdIn, _T("CONIN$"), _T("r"), stdin);
_tfreopen_s(&fpStdOut, _T("CONOUT$"), _T("w"), stdout);
_tfreopen_s(&fpStdErr, _T("CONOUT$"), _T("w"), stderr);

Once opened and initialized, the console can be used just like you do in a normal text-based application. Note that you need to explicitly release both the console and the streams you opened.

// Release the console
FreeConsole();

// Release the streams
fclose(stdin);
fclose(stdout);
fclose(stderr);

It’s a good idea to add this code inside an #ifdef statement, in order to remove this code (as well as the printf functions) from the release version.

Source code: http://www.InsaneDevelopers.net/downloads/Sources/CreatingAConsole.zip