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 #include #include 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
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
#include
#include
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?