Search code examples
c++console-applicationbackground-color

Change background color of C++ console app


How do I go about changing the foreground color of a console app if I wanted to use colors other than green, red, blue? Below is a portion of my code:

case GreenFlag:
    indicator = GreenFlag;
    SetConsoleTextAttribute(GetStdHandle (STD_OUTPUT_HANDLE), BACKGROUND_GREEN);
    cout << "Green message" << endl;
    break;
case OrangeFlag:
    indicator = OrangeFlag;
    // SetConsoleTextAttribute(GetStdHandle (STD_OUTPUT_HANDLE), BACKGROUND_ORANGE);
    cout << "Orange message" << endl;
    break;
case RedFlag:
    indicator = RedFlag;
    SetConsoleTextAttribute(GetStdHandle (STD_OUTPUT_HANDLE), BACKGROUND_RED);
    cout << "Red message" << endl;
    break;
case WhiteFlag:
    indicator = WhiteFlag;
    // SetConsoleTextAttribute(GetStdHandle (STD_OUTPUT_HANDLE), BACKGROUND_WHITE);
    cout << "White message" << endl;
    break;
etc...

Solution

  • You asked:

    how to use colors other than green, red, blue?

    You may combine the flags to create new colors:

    An application can combine the foreground and background constants to achieve different colors. For example, the following combination results in bright cyan text on a blue background.

    FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY | BACKGROUND_BLUE

    If no background constant is specified, the background is black, and if no foreground constant is specified, the text is black. For example, the following combination produces black text on a white background.

    BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED

    Beyond that, you may set colors individually on each char and/or modify the screen buffer attributes:

    Each screen buffer character cell stores the color attributes for the colors used in drawing the foreground (text) and background of that cell. An application can set the color data for each character cell individually, storing the data in the Attributes member of the CHAR_INFO structure for each cell. The current text attributes of each screen buffer are used for characters subsequently written or echoed by the high-level functions.

    An application can use GetConsoleScreenBufferInfo to determine the current text attributes of a screen buffer and the SetConsoleTextAttribute function to set the character attributes. Changing a screen buffer's attributes does not affect the display of characters previously written. These text attributes do not affect characters written by the low-level console I/O functions (such as the WriteConsoleOutput or WriteConsoleOutputCharacter function), which either explicitly specify the attributes for each cell that is written or leave the attributes unchanged.

    For documentation and example see: https://learn.microsoft.com/en-us/windows/console/using-the-high-level-input-and-output-functions