I am trying to make a function having a text color and a background color attribute. The text color attribute just sets the color of the text to follow while the background color has to change the background color of whole console window.
The problem is that the SetConsoleTextAttribute()
function only changes the background color of a block of text but not of the whole console window. While the problem with system("Color code")
is that it changes the color of any pre-written text also.
what I want to do is this:
int main()
{
setColor("Red","Blue");
//custom function setColor() to set text color Red and Console's color Blue.
cout << "This is Red text on a Blue console window" << endl;
setColor("Yellow","Black"); /*now the whole console's color should turn Black, the color
of pre-written text above remains Red and the color of text
to follow should be Yellow.*/
cout << "This is Yellow text on a Black console window, The previous text is still Red";
return 0;
}
I have tried mixing both system()
and setConsoleTextAttribute
functions to achieve this but I failed to preserve the color of pre-written text while changing color of the text to follow.
So, is there a way of making a function which does the same thing as the setColor()
function did in this example?
You will need to implement this yourself. The Windows Console API can help, all the functions are documented here.
You can read the colors of the currently displayed characters with
ReadConsoleOutputAttributes
. You can change them to the new background color withWriteConsoleOutputAttributes
.