1

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.

Ruashua
  • 27
  • 4
  • Please refer this https://stackoverflow.com/questions/30645675/how-to-change-colour-of-a-specific-output-on-console-in-c – Fairoz Jun 18 '19 at 21:16
  • This looks like it is exactly what I am doing already, which does not produce the results I am looking for. If I set SetConsoleTextAttribute(hConsole, 7); Run from CMD, the consoles background color is black, text background color is black, text color is white. Everything is fine. If I run it from powershell, I get a powershells darkblue background, my text will have a black background, my text color will be white. Not what I want. I want the text background to match the consoles background color no matter what console it is ran from (CMD or Powershell) – Ruashua Jun 18 '19 at 21:26
  • 2
    Can you [get the previous background colour](https://stackoverflow.com/questions/8578909/how-to-get-current-console-background-and-text-colors) and set the new background colour to be the same as it already was? – user253751 Jun 18 '19 at 22:40
  • So you want to change only foreground color in any console ( PS or CMD). correct me if I am wrong. – Nirav Mistry Jun 19 '19 at 04:03
  • Thank you immibis, you answered my question – Ruashua Jun 19 '19 at 20:59

1 Answers1

0

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!";
Ruashua
  • 27
  • 4