From f5929dd5dccff1b46f79d7f7e485810d1efdea47 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ond=C5=99ej=20=C4=8Cert=C3=ADk?= Date: Tue, 17 Sep 2024 14:53:22 -0600 Subject: [PATCH] Attach to the console on Windows This makes `std::cout` working again after switching to a GUI application in https://github.com/prefix-dev/pixi/pull/2067. It still does not open a console when launched from the Windows Explorer, but when launched from a terminal, it will now print to the terminal again, as before. --- examples/cpp-sdl/src/main.cc | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/examples/cpp-sdl/src/main.cc b/examples/cpp-sdl/src/main.cc index a6df74b07..40a5751da 100644 --- a/examples/cpp-sdl/src/main.cc +++ b/examples/cpp-sdl/src/main.cc @@ -1,7 +1,20 @@ #include #include +#ifdef _WIN32 +# include +#endif int main( int argc, char* args[] ) { +#ifdef _WIN32 + // Attach to the parent console if running from a console + if (AttachConsole(ATTACH_PARENT_PROCESS)) { + // Redirect stdout to the console + FILE* fp; + freopen_s(&fp, "CONOUT$", "w", stdout); + } +#endif + + std::cout << "Starting..." << std::endl; // Initialize SDL if( SDL_Init( SDL_INIT_VIDEO ) < 0 ) @@ -78,5 +91,12 @@ int main( int argc, char* args[] ) { SDL_DestroyWindow(window); SDL_Quit(); + std::cout << "End." << std::endl; + +#ifdef _WIN32 + // Detach from the console + FreeConsole(); +#endif + return 0; }