I am playing around with some OpenGL, using SDL to handle the window / input etc. Currently I am displaying any information I want to see to a HUD. Well, this is getting over-cumbersome, and I was wondering if there is a simple way to open up a separate console window to report this information to me. I am still new to C++ so go easy on me if this is an obvious one.
The following code is for Windows. I always find it handy to keep around the ability to create a console window on demand:
int hConHandle;
intptr_t lStdHandle;
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 = 500;
SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), coninfo.dwSize);
// redirect unbuffered STDOUT to the console
lStdHandle = (intptr_t)GetStdHandle(STD_OUTPUT_HANDLE);
hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
fp = _fdopen( hConHandle, "w" );
*stdout = *fp;
setvbuf( stdout, NULL, _IONBF, 0 );
// redirect unbuffered STDIN to the console
lStdHandle = (intptr_t)GetStdHandle(STD_INPUT_HANDLE);
hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
fp = _fdopen( hConHandle, "r" );
*stdin = *fp;
setvbuf( stdin, NULL, _IONBF, 0 );
// redirect unbuffered STDERR to the console
lStdHandle = (intptr_t)GetStdHandle(STD_ERROR_HANDLE);
hConHandle = _open_osfhandle(lStdHandle, _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();
//Keep our window in focus
SetForegroundWindow(m_hWnd); // Slightly Higher Priority
SetFocus(m_hWnd); // Sets Keyboard Focus To The Window
This code assumes that the HWND
is in a variable called m_hWnd
; it's copied from a class wrapper I use. How you get the HWND
from SDL is up to you, however.
To free the console, call this:
FreeConsole();
AllocConsole
and FreeConsole
are Win32 API functions.
In Linker -> System in your project's properties, check that the SubSystem is "Console (/SUBSYSTEM:CONSOLE)". That causes a separate console window to be brought up when you run your program. If your current entry point isn't main
, then you'll need to change it to that if you do this though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With