Re: very simple question of how to get the console color
Posted 31 August 2009 - 07:17 AM
Using system to set the colors is really not a wonderful idea (it works though). You really should be using the API rather than exiting out to the system to do your dirty work for you. One good reason is that you can't get the current colors using the system command (unless you write your own utility to do it for you).
SO... how might you use the API? Well you can look at my snippet here which covers a number of useful functions. However I did not do a getConsoleColors() routine...
However if you look at the setColor() routine -- it needs to get the current text attributes so that it can set the forground color without affecting the background color... all we need to do is modify this routine to return the text attribute byte (the color). If we want we can even brake it up into a "getForground()" and "getBackground()"
int forg, back;
forg = getForground();
back = getBackground();
printf("forground color: %d\nBackground color: %d\n", forg, back);
//This will set the forground color for printing in a console window.
WORD wColor = 0;
//We will need this handle to get the current background attribute
HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
//We use csbi for the wAttributes word.
//return the wAttributes data
wColor = (csbi.wAttributes & 0xFF);
//Mask out all but the lower nibble
return GetColor() & 0x0F;
// Shift down one nibble (4bits) and then mask off everything else
return (GetColor() >> 4) & 0x0F;