Skip to content

AllocConsole

A snippet that attaches a console to a GUI process and redirects stdout into it.

Published May 5, 1998

The classic trick for giving a windowless (GUI-subsystem) program a real console at runtime. AllocConsole() creates the console window, then _open_osfhandle and _fdopen wrap the new standard output handle in a CRT FILE stream so ordinary printf calls land there instead of nowhere. Use it when you want debug output from a service or GUI app without relinking as a console application.

#include <Windows.H>
#include <StdIO.H>
#include <fcntl.h>
#include "IO.H"


{
	AllocConsole();

	//Redirect stdout to the newly allocated console.
	int hCrt, i;
	FILE *hf;
	hCrt = _open_osfhandle((long) GetStdHandle(STD_OUTPUT_HANDLE), _O_TEXT);
	hf = _fdopen( hCrt, "w" );
	*stdout = *hf;
	i = setvbuf( stdout, NULL, _IONBF, 0);
}
An unhandled error has occurred. Reload 🗙