0

I'm fairly new to programming and I try to use colors in the console but it doesn't have many option so I would like to change the 16 base colors so I get personalised ones. I found this code but it doesn't really work (the colors dont changes).

CONSOLE_SCREEN_BUFFER_INFOEX info;
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfoEx(hConsole, &info);

info.ColorTable[0] = RGB(0,0,0);
...
info.ColorTable[3] = RGB(135, 206, 235);
...
info.ColorTable[15] = RGB (25,25,25);

SetConsoleScreenBufferInfoEx(hConsole, &info);` 
dasunse
  • 2,839
  • 1
  • 14
  • 32
  • P.S. first time using a forum so I probably did something wrong in the post already – Jonathan Calvin Oct 24 '19 at 03:22
  • Only a little. Always prefix every line of code with at least 4 spaces, or surround it with 3 backticks in a row, on their own line. This is a backtick: ` – Caius Jard Oct 24 '19 at 03:40

2 Answers2

1

I always thought to change the console colors on a word by word basis you had to print out certain escape sequences of characters. Was quite surprised to learn from How to echo with different colors in the Windows command line that it's only this year or so that this has become a thing in the native command prompt. Maybe I'm thinking of the Commodore Amiga when I thought this had been possible for decades in DOS prompts

The accepted answer in the above linked question links to a github project for changing the colors; perhaps you can incorporate this into your app in some way to allow customizing of the colors

Caius Jard
  • 72,509
  • 5
  • 49
  • 80
1

Before calling GetConsoleScreenBufferInfoEx, you have to first set cbSize of CONSOLE_SCREEN_BUFFER_INFOEX. The simplest way is something like that:

//Example of changing palette
int main()
{
    HANDLE outH = GetStdHandle(STD_OUTPUT_HANDLE); //It doesn't make sense to everytime call GetStdHandle
    CONSOLE_SCREEN_BUFFER_INFOEX oldOne, newBuff; 
    oldOne.cbSize = sizeof(CONSOLE_SCREEN_BUFFER_INFOEX);
    GetConsoleScreenBufferInfoEx(outH, &oldOne);
    oldOne.srWindow.Bottom++; //After getting current buffer window usually makes smaller
    newBuff = oldOne; //Copy your current to new

    /* Edit your new buffer */

    //Set your dreamed buffer
    SetConsoleScreenBufferInfoEx(outH, &newBuff);

    /* Do something */

    //restore to defaults
    SetConsoleScreenBufferInfoEx(outH, &oldOne);
    return 0;
}

As you can see, all that I changed is oldOne.cbSize = sizeof(CONSOLE_SCREEN_BUFFER_INFOEX). It's important because in another way GetConsoleScreenBufferInfoEx will failure. For more information go there. Pay attention that after changing your console palette, you will never restore it, so better add some lines to your code to save your previous one.