Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enabling ANSI escape code processing on the modern Windows command line? [C]

I've heard that modern Windows consoles support ANSI escape codes (COLORS), but you have to enable them.

Using the 19042.746 build of Windows 10, it should just be a simple affair of enabling it using the SetConsoleMode(consoleHandle, ENABLE_VIRTUAL_TERMINAL_PROCESSING); // from windows.h, but after setting it, it still doesn't support ANSI escape colors. What am I missing?

Real life examples

HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleMode(hConsole, ENABLE_VIRTUAL_TERMINAL_PROCESSING);
printf("\033[32mThis is green");

Prints out

[31mThis is green

Sources:

  • SetConsoleMode function

  • Bash tips: Colors and formatting (ANSI/VT100 Control sequences)

like image 577
Luka K. Avatar asked Aug 12 '26 05:08

Luka K.


1 Answers

You also need to add ENABLE_PROCESSED_OUTPUT. You need to use GetConsoleMode first to get the current mode (it usually contains ENABLE_PROCESSED_OUTPUT), and then add ENABLE_VIRTUAL_TERMINAL_PROCESSING to the mode:

HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
DWORD mode = 0;
GetConsoleMode(hConsole, &mode); //
SetConsoleMode(hConsole, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
printf("\033[32mThis is green");

Result:

Enter image description here

like image 184
Drake Wu Avatar answered Aug 13 '26 19:08

Drake Wu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!