Home > Back-end >  How to colorize console background with COLOREF RGB code?
How to colorize console background with COLOREF RGB code?

Time:11-01

Here I ask you : How are we supposed to colorize the console background with only the COLOREF datatype as a parameter?

The most common way of colorizing background is by using windows header function system("color --")

However, this way is not possible, and I am tasked to find out if we can colorize the console background using only the COLOREF datatype.

I did some research, and what I came across was SetConsoleAttribute(), and the windows header function system("color --").

This is what I expect my code to be:

COLOREF data = RGB(255, 0, 0);//red, basically

SetConsoleBackground(HDC *console, data);

Any way of doing this? Thanks in advance.

CodePudding user response:

[NEW ANSWER (edit)] So @IInspectable pointed out the the console now supports 24-bit full rgb colors so i did some research and managed to make it work. This is how i solved it:

#include <Windows.h>
#include <string>
struct Color
{
    int r;
    int g;
    int b;
};

void SetBackgroundColor(const Color& aColor)
{
    std::string modifier = "\x1b[48;2;"   std::to_string(aColor.r)   ";"   std::to_string(aColor.g)   ";"   std::to_string(aColor.b)   "m";
    printf(modifier.c_str());
}

void SetForegroundColor(const Color& aColor)
{
    std::string modifier = "\x1b[38;2;"   std::to_string(aColor.r)   ";"   std::to_string(aColor.g)   ";"   std::to_string(aColor.b)   "m";
    printf(modifier.c_str());
}
int main()
{
    // Set output mode to handle virtual terminal sequences
    HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);

    DWORD dwMode = 0;
    GetConsoleMode(hOut, &dwMode);

    dwMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
    SetConsoleMode(hOut, dwMode);

    SetForegroundColor({ 100,100,20 });
    SetBackgroundColor({ 50,100,10 });
    printf("Hello World\n");

    system("pause");
}

[OLD ANSWER] The console only supports 256 different color combinations defined with a WORD which is 8 bits long. The background color is stored in the 4 higher bits. This means the console only has support for 16 different colors:

enum class Color : int
{
    Black = 0,
    DarkBlue = 1,
    DarkGreen = 2,
    DarkCyan = 3,
    DarkRed = 4,
    DarkPurple = 5,
    DarkYellow = 6,
    DarkWhite = 7,
    Gray = 8,
    Blue = 9,
    Green = 10,
    Cyan = 11,
    Red = 12,
    Purple = 13,
    Yellow = 14,
    White = 15,
};

To set the background color of the typed characters, you could do:

void SetWriteColor(const Color& aColor)
{
    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleTextAttribute(hConsole, static_cast<WORD>(aColor) << 4);
}
  • Related