Search code examples
c++windowswinapi

Redirect standard output to console in GUI application


I have a C++ application that I compile in GUI mode, and sometimes I run it from the console for debugging purpose. Since normally it doesn't write anything to the console, I attached the console and use freopen() to redirect standard output to the console using the following code:

#include <iostream>
#include <cstdio>
#include <windows.h>

int WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
    // Attach to the parent console
    if (AttachConsole(ATTACH_PARENT_PROCESS)) {
        // Redirect stdout and stderr to the console
        freopen("CONOUT$", "w", stdout);
        freopen("CONOUT$", "w", stderr);
    }
    std::cout << "print to stdout" << std::endl;
    std::cerr << "print to stderr" << std::endl;

    return 0;
}

However, I would like to do it using WinAPI directly instead of freopen().

I tried to use SetStdHandle() or following https://asawicki.info/news_1326_redirecting_standard_io_to_windows_console without luck, it prints nothing compared to freopen, which works.

In addition, when the program running the terminal doesn't detect well that it's currently running and if I press Enter, the terminal detects and shows me the prompt instead of sending it to the program. Can it be fixed as well?


Solution

  • Based on answers in comments:

    The c++ standard streams are managed internally by the c runtime library. SetStdHandle affects other WinAPI calls that use the handle, but not the c++ runtime's streams. That's why I need to use freopen() or similar functions from libc to change the c++ runtime streams.