如何将控制台输出的文本颜色更改为红色,但如果从Powershell或CMD运行,背景将保持相同的颜色

How can you change the text color of console output to red, but background remains the same color if ran from Powershell or CMD

本文关键字:颜色 运行 CMD 背景 Powershell 文本 输出 控制台 红色 如果      更新时间:2023-10-16

在Windows中,我希望我的程序将文本输出到控制台,只为程序的一行为红色。但是,我希望无论程序是从Powershell还是cmd运行,背景都保持不变。

我试过使用句柄

HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsole, color);
cout << text;

这将更改背景。如果我匹配cmd的默认黑色背景(如果颜色为0-15(,它会在Powershell的默认深蓝色背景上显示Powershell中黑色背景的文本。

我希望有人从CMD或Powershell运行该程序,背景颜色不会改变,但文本会改变。

多亏了immibis,我得到了答案。我需要获取当前的控制台颜色,然后我可以从那里开始。

CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
int defaultColor = 7;
int redColor = 12;
if (GetConsoleScreenBufferInfo(hConsole, &csbiInfo)) //This gets the color
{
   defaultColor = csbiInfo.wAttributes;  //This is where the current color is stored
   redColor = (defaultColor / 16) * 16 + 12;  //Keeps the background color, sets the text to red
}
SetConsoleTextAttribute(hConsole, redColor);
cout << "This is red!n";
SetConsoleTextAttribute(hConsole, defaultColor);
cout << "Back to Normal!";