如何更改整个控制台的背景颜色而不影响Windows操作系统上的c ++中的文本颜色

时间:2016-12-25 22:18:40

标签: c++ windows colors background-color windows-console

我正在尝试创建一个具有文本颜色和背景颜色属性的函数。文本颜色属性只设置要跟随的文本的颜色,而背景颜色必须更改整个控制台窗口的背景颜色。

问题是SetConsoleTextAttribute()函数只更改了文本块的背景颜色,而不是整个控制台窗口的背景颜色。虽然system("Color code")的问题在于它也会改变任何预先写好的文本的颜色。

我想做的是:

 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;
 }

我尝试混合使用system()setConsoleTextAttribute函数来实现这一目标,但是在更改要跟随的文本颜色时,我未能保留预先写入文本的颜色。

那么,是否有一种方法可以创建一个与setColor()函数在此示例中执行相同操作的函数?

1 个答案:

答案 0 :(得分:1)

您需要自己实施。 Windows Console API可以提供帮助,所有功能都是documented here

您可以使用ReadConsoleOutputAttributes阅读当前显示的字符的颜色。您可以使用WriteConsoleOutputAttributes将其更改为新的背景颜色。