Create a console from within a non-console .NET application.
- by pauldoo
How can I open a console window from within a non-console .NET application (so I have a place for System.Console.Out and friends when debugging)?
In C++ this can be done using various Win32 APIs:
/*
EnsureConsoleExists() will create a console
window and attach stdout (and friends) to it.
Can be useful when debugging.
*/
FILE* const CreateConsoleStream(const DWORD stdHandle, const char* const mode)
{
const HANDLE outputHandle = ::GetStdHandle(stdHandle);
assert(outputHandle != 0);
const int outputFileDescriptor = _open_osfhandle(reinterpret_cast<intptr_t>(outputHandle), _O_TEXT);
assert(outputFileDescriptor != -1);
FILE* const outputStream = _fdopen(outputFileDescriptor, mode);
assert(outputStream != 0);
return outputStream;
}
void EnsureConsoleExists()
{
const bool haveCreatedConsole = (::AllocConsole() != 0);
if (haveCreatedConsole) {
/*
If we didn't manage to create the console then chances are
that stdout is already going to a console window.
*/
*stderr = *CreateConsoleStream(STD_ERROR_HANDLE, "w");
*stdout = *CreateConsoleStream(STD_OUTPUT_HANDLE, "w");
*stdin = *CreateConsoleStream(STD_INPUT_HANDLE, "r");
std::ios::sync_with_stdio(false);
const HANDLE consoleHandle = ::GetStdHandle(STD_OUTPUT_HANDLE);
assert(consoleHandle != NULL && consoleHandle != INVALID_HANDLE_VALUE);
CONSOLE_SCREEN_BUFFER_INFO info;
BOOL result = ::GetConsoleScreenBufferInfo(consoleHandle, &info);
assert(result != 0);
COORD size;
size.X = info.dwSize.X;
size.Y = 30000;
result = ::SetConsoleScreenBufferSize(consoleHandle, size);
assert(result != 0);
}
}