Create a console from within a non-console .NET application.

Posted by pauldoo on Stack Overflow See other posts from Stack Overflow or by pauldoo
Published on 2010-05-21T14:09:01Z Indexed on 2010/05/21 14:10 UTC
Read the original article Hit count: 171

Filed under:
|

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);
    }
}

© Stack Overflow or respective owner

Related posts about .NET

Related posts about console