Skip to content

Commit 0fed2ab

Browse files
authored
Enable ANSI colors on Windows 10+
On older versions function will silently fail without any ill effects
1 parent da5303c commit 0fed2ab

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed

main.cpp

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,13 @@
1919
#include <signal.h>
2020
#endif
2121

22+
#if defined (_WIN32)
23+
#pragma comment(lib,"kernel32.lib")
24+
extern "C" __declspec(dllimport) void* __stdcall GetStdHandle(unsigned long nStdHandle);
25+
extern "C" __declspec(dllimport) int __stdcall GetConsoleMode(void* hConsoleHandle, unsigned long* lpMode);
26+
extern "C" __declspec(dllimport) int __stdcall SetConsoleMode(void* hConsoleHandle, unsigned long dwMode);
27+
#endif
28+
2229
#define ANSI_COLOR_RED "\x1b[31m"
2330
#define ANSI_COLOR_GREEN "\x1b[32m"
2431
#define ANSI_COLOR_YELLOW "\x1b[33m"
@@ -933,6 +940,13 @@ int main(int argc, char ** argv) {
933940

934941
// set the color for the prompt which will be output initially
935942
if (params.use_color) {
943+
#if defined (_WIN32)
944+
// Enable ANSI colors on Windows 10+
945+
unsigned long dwMode = 0;
946+
void* hConOut = GetStdHandle((unsigned long)-11); // STD_OUTPUT_HANDLE (-11)
947+
if (hConOut && hConOut != (void*)-1 && GetConsoleMode(hConOut, &dwMode))
948+
SetConsoleMode(hConOut, dwMode | 0x4); // ENABLE_VIRTUAL_TERMINAL_PROCESSING (0x4)
949+
#endif
936950
printf(ANSI_COLOR_YELLOW);
937951
}
938952

0 commit comments

Comments
 (0)