I want to set the text color of the console to a RGB color. I created a function to get the ColorTable of the console and change the colors in it, but it doesn't work. I don't know how to set the text color to a value from the color table so I just change the whole color table, but it doesn't do anything.
void setColor(int r, int g, int b)
{
COLORREF cr;
cr = RGB(r, g, b);
PCONSOLE_SCREEN_BUFFER_INFOEX ci;
CONSOLE_SCREEN_BUFFER_INFOEX cir;
ci = ○
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfoEx(hConsole , ci);
cout <<hex<< ci->ColorTable[2];
for(int i=0;i<16;i++){
ci->ColorTable[i] = cr;
}
SetConsoleScreenBufferInfoEx(hConsole, ci);
GetConsoleScreenBufferInfoEx(hConsole , ci);
cout <<endl << ci->ColorTable[2];
}
In main()
I invoke the function multiple times, but the output is the same every call and the color doesn't change. SetConsoleScreenBufferInfoEx()
and GetConsoleScreenBufferInfoEx()
don't seem to do anything, ci
remains unchanged when they are called.
What do I do wrong?
Also, if it worked I assume the background color would also get changed because I change the whole pallette, so how do I set the text color to a specific value from the color table, e.g. i put ci->ColorTable[2] = cr;
in the changeColor()
function instead of the for loop, how can I set the text color to the color that is now stored in ColorTable[2]
?
A Windows console color table looks like this:
To set background colors you have to combine the foreground color code with the background color code using this equation:
if you want to set a text color that has a blue background and white text you simply look up the color code in the table. Blue is 1 and white is 15;
Hence
int backgroundcolor=1;
andint foregroundcolor=15;
You need to use
SetConsoleTextAttribute
to set the current text color and background color, see http://msdn.microsoft.com/en-us/library/windows/desktop/ms686047(v=vs.85).aspx for details.