Hi again, so guys I want to add some color to my text but all the explanations I find are some links to complicated ways of doing it with almost no explanation of the operators functions and so on. Could you show me an easy way to make for example a sentance a different color than the usual text in a program, or if there is no simple way could you explan how it is done so that I dont need to just copy paste and wonder what I just did but actualy understand it. :)

So let me just check if I got it correctly first I save the current color with

#include <stdio.h> 
#include <windows.h> 

int main ( void )
{
  HANDLE h = GetStdHandle ( STD_OUTPUT_HANDLE );
  WORD wOldColorAttrs;
  CONSOLE_SCREEN_BUFFER_INFO csbiInfo; 

  GetConsoleScreenBufferInfo(h, &csbiInfo);
  wOldColorAttrs = csbiInfo.wAttributes; 

By the way does it have to say void in the brackets on int main.

And then for every line I want to color I Put

 SetConsoleTextAttribute ( h, FOREGROUND_RED | FOREGROUND_INTENSITY );

Before it and

SetConsoleTextAttribute ( h, wOldColorAttrs);

after.
Also do I have to use printf to get the text because I am currently using the cout<< method?
Oh, and why are there only 3 colors is that really the limit :/

Member Avatar for iamthwee

There should be the following color constants...

COLOR_BLACK
COLOR_RED
COLOR_GREEN
COLOR_YELLOW
COLOR_BLUE
COLOR_MAGENTA
COLOR_CYAN
COLOR_WHITE

Unfortunately, I can't test it as I'm not using windows :)

This doc page may prove useful to you.

By the way does it have to say void in the brackets on int main.

No. In fact, in C++ it shouldn't have void there.

And then for every line I want to color I Put

SetConsoleTextAttribute ( h, FOREGROUND_RED | FOREGROUND_INTENSITY );

>

Before it and

SetConsoleTextAttribute ( h, wOldColorAttrs);

after.

Actually, you should be able to set the attribute once for a block of rows, and only restore the original settings at the end of that - assuming you want to go back to the previous settings at all...

Also do I have to use printf to get the text because I am currently using the cout<< method?

I would expect that either would work, actually, though I'm not sure either of them is really correct. The actual Windows API function is WriteConsole(), but I expect that the C and C++ stream I/O functions are calling that themselves.

Oh, and why are there only 3 colors is that really the limit :/

No, it isn't; you can combine the bitfields for the colors to get different shades. For example, FOREGROUND_BLUE | FOREGROUND_GREEN should give cyan text.

Wow thanks guys I think I can manage now , and Schol-R-LEA thanks a lot for the thorough explanation ^_^

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.