Reputation: 31
I'm trying to enable ANSI color support for created console screen buffer via CreateConsoleScreenBuffer()
.
hConsole = CreateConsoleScreenBuffer(GENERIC_READ | GENERIC_WRITE, 0, NULL, CONSOLE_TEXTMODE_BUFFER, NULL);
DWORD dwMode = 0;
GetConsoleMode(hConsole, &dwMode);
dwMode |= ENABLE_EXTENDED_FLAGS;
SetConsoleMode(hConsole, dwMode);
dwMode = 0;
GetConsoleMode(hConsole, &dwMode);
dwMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
SetConsoleMode(hConsole, dwMode);
SetConsoleActiveScreenBuffer(hConsole);
It seems like SetConsoleMode() isn't doing anything, I can write it to buffer as I intended, but if I try to write any ANSI Escape codes, it looks like this
If I'm not in buffer created by CreateConsoleScreenBuffer()
, ANSI Escape codes are working as expected.
EDIT: I'm on Windows 10, 19041.388; C++14, MinGW-64 compiler
Upvotes: 2
Views: 3073
Reputation: 6289
Virtual terminal sequences are control character sequences that can control cursor movement, color/font mode, and other operations when written to the output stream. Sequences may also be received on the input stream in response to an output stream query information sequence or as an encoding of user input when the appropriate mode is set.
You can use GetConsoleMode and SetConsoleMode functions to configure this behavior.
From ENABLE_VIRTUAL_TERMINAL_PROCESSING, we can use WriteFile
or WriteConsole
to achieve.
Some code:
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
HANDLE hConsole_c = CreateConsoleScreenBuffer(GENERIC_READ | GENERIC_WRITE, 0, NULL, CONSOLE_TEXTMODE_BUFFER, NULL);
SetConsoleActiveScreenBuffer(hConsole_c);
DWORD dwMode = 0;
GetConsoleMode(hConsole_c, &dwMode);
dwMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
SetConsoleMode(hConsole_c, dwMode);
const char* str = "\x1b[31mThis text has restored the foreground color only.\r\n";
DWORD len = strlen(str);
DWORD dwBytesWritten = 0;
WriteConsole(hConsole_c, str, len, &dwBytesWritten, NULL);
Debug:
Upvotes: 1
Reputation: 540
You could use this:
#include <windows.h>
#include <iostream>
void Color(int color=0x07)
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color);
}
int main()
{
Color(0x0A/*Black bg green Fg*/);
std::cout << "Hello";
Color();
std::cout << ",";
Color(0xAC/*Green bg red Fg*/);
std::cout << "World";
Color(/*Black bg white Fg*/);
}
For more information about the colors:
Color attributes are specified by TWO hex digits -- the first corresponds to the background; the second the foreground. Each digit can be any of the following values:
0 = Black 8 = Gray
1 = Blue 9 = Light Blue
2 = Green A = Light Green
3 = Aqua B = Light Aqua
4 = Red C = Light Red
5 = Purple D = Light Purple
6 = Yellow E = Light Yellow
7 = White F = Bright White
Upvotes: 3