Skip to content

Instantly share code, notes, and snippets.

@code-disaster
Last active November 2, 2021 08:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save code-disaster/46c63d6dac313eaffb1c64b412d029e4 to your computer and use it in GitHub Desktop.
Save code-disaster/46c63d6dac313eaffb1c64b412d029e4 to your computer and use it in GitHub Desktop.
An existing console printing *something* for windowed applications
// To output stderr/stdout to an existing console for windowed applications. It works.
// Sometimes. Even with UTF-8 and terminal colors, if you are lucky.
void conout_initialize()
{
if (!IsDebuggerPresent()) {
// Win32 console output is awful! This tries to rewire stdout so that we
// get to see *something* in the CMD prompt.
if (AttachConsole(ATTACH_PARENT_PROCESS) != 0) {
FILE * stdout_redirect;
freopen_s(&stdout_redirect, "CONOUT$", "w", stdout);
FILE * stderr_redirect;
freopen_s(&stderr_redirect, "CONOUT$", "w", stderr);
HANDLE con_out = CreateFile(
TEXT("CONOUT$"),
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
nullptr,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
nullptr
);
SetStdHandle(STD_OUTPUT_HANDLE, con_out);
SetConsoleOutputCP(CP_UTF8);
// clears current line, moves cursor to the left
fprintf(stdout, "\x1b[2K\r");
}
}
}
void conout_shutdown()
{
fprintf(stdout, "\x1b[2K\r\x1b[32m[Bye!]\x1b[0m\r\n");
fflush(stdout);
if (HWND console = GetConsoleWindow()) {
// sends a final return key event to close the console window
SendMessage(console, WM_CHAR, VK_RETURN, 0);
FreeConsole();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment