Recently I'm messing around with colors in the terminal.
I'm using a sample program from here to test this out in different consoles.
In the Windows Terminal
from the Microsoft Store, you can see colors:
Below is the exact same program, but in cmd.exe
in which you can't see the colors.
In the same exact console however, when I run the command gcc
I do get additional colors (white and red, in fact):
Now my question is, what does gcc
do differently, to still be able to print colored text? I can't find any other way to get colored text on the console than written on the linked site above.
This question can help you:
This is the list for functions you needed (in this example we use red in green):
GetConsoleScreenBufferInfo
and pass the lpConsoleScreenBufferInfo->dwCursorPosition
to WriteConsoleOutputAttribute()
and then use the WriteConsoleOutputCharacter
with the same length passed to nLength
.
Code: HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO consoleBuffer;
GetConsoleScreenBufferInfo (hStdOut, &consoleBuffer);
const char *string = "AABBCCDDEEFFGG";
int length = strlen(string);
DWORD written;
WriteConsoleOutputAttribute(hStdOut, (WORD*)(FOREGROUND_RED | BACKGROUND_GREEN), length, consoleBuffer.dwCursorPosition, &written);
WriteConsoleOutputCharacter(hStdOut, string, length, consoleBuffer.dwCursorPosition, &written);
system("color 0F")
or use GetConsoleScreenBufferInfo
and pass the lpConsoleScreenBufferInfo->dwCursorPosition
to SetConsoleTextAttribute()
function.
Code for SetConsoleTextAttribute()
: HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO consoleBuffer;
const char* string = "AABBCCDDEEFFGG";
int length = strlen(string);
DWORD written;
GetConsoleScreenBufferInfo(hStdOut, &consoleBuffer);
SetConsoleTextAttribute(hStdOut, FOREGROUND_RED | BACKGROUND_GREEN);
WriteConsoleOutputCharacter(hStdOut, string, length, consoleBuffer.dwCursorPosition, &written);
SetConsoleTextAttribute(hStdOut, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | 0);
Note: You can use WriteConsole()
instead of using WriteConsoleOutputCharacter()
function.
Don't forget to restore the mode!