简体   繁体   中英

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

In Windows, I want my program to output text to console to be red for only one line of the program. But, I want the background to remain unchanged no matter if the program ran from Powershell or cmd.

I have tried using HANDLE

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

This will change the background. If I match cmd's default black background (if color is 0-15), it displays the text with a black background in Powershell over Powershell's default dark blue background.

I would like it so if someone runs the program from either CMD or Powershell, the background color does not change but the text does change.

Thanks to immibis I got my answer. I needed to get the current console color, then I could go from there.

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!";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM