Hybrid GUI/Console App
Thibault Genessay
tibogens at gmail.com
Fri Apr 18 00:47:39 PDT 2008
Hi Guys
> ::AttachConsole(ATTACH_PARENT_PROCESS) could help here but this function
> fails for me (Windows 2003) with "invalid handle" error and, anyhow, it's
> XP and later only. And in fact even allocating a new console doesn't work
> (the console does appear but printf() still does nothing).
>
> So it unfortunately seems that the usefulness of this method under Windows
> is indeed limited to console applications which sometimes need to show GUI.
Attached is a bunch of code that creates a console for a process that
was linked with the /SUBSYSTEM:WINDOWS. I use it on Win XP and it
works as expected. Not so broken, after all.
Regards
Thibault
void allocateConsole()
{
int hConHandle;
HANDLE stdHandle;
CONSOLE_SCREEN_BUFFER_INFO coninfo;
FILE *fp;
// allocate a console for this app
AllocConsole();
// set the screen buffer to be big enough to let us scroll text
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE),
&coninfo);
coninfo.dwSize.Y = 300;
SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE),
coninfo.dwSize);
// redirect unbuffered STDOUT to the console
stdHandle = GetStdHandle(STD_OUTPUT_HANDLE);
hConHandle = _open_osfhandle((intptr_t)stdHandle, _O_TEXT);
fp = _fdopen( hConHandle, "w" );
*stdout = *fp;
setvbuf( stdout, NULL, _IONBF, 0 );
// redirect unbuffered STDIN to the console
stdHandle = GetStdHandle(STD_INPUT_HANDLE);
hConHandle = _open_osfhandle((intptr_t)stdHandle, _O_TEXT);
fp = _fdopen( hConHandle, "r" );
*stdin = *fp;
setvbuf( stdin, NULL, _IONBF, 0 );
// redirect unbuffered STDERR to the console
stdHandle = GetStdHandle(STD_ERROR_HANDLE);
hConHandle = _open_osfhandle((intptr_t)stdHandle, _O_TEXT);
fp = _fdopen( hConHandle, "w" );
*stderr = *fp;
setvbuf( stderr, NULL, _IONBF, 0 );
// make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog
// point to console as well
std::ios::sync_with_stdio();
}
More information about the wx-users
mailing list