C++ Different Text Colour

Hi everyone,

I'm making a console app in C++ (MSVS 2010) and I was wondering how I could make different sentences or letters be a different colour all on one screen, for example:

1
2
3
4
5
6
7
string a;
string b = "You typed in: ";

cin << a; // white text blue backround which is system("color 1f");//
cout >> b; cout >> a; //string b to be   system("color 1f"); but string a to be   system("color 1a"); 



When I use system("color 1a"); it changes everything, so how can I just limit the command to a string?

Thanks for any help,

Muhasaresa
Last edited on
You can't, at least not like that (you could attempt to use ANSI control characters, but IIRC windows doesn't support those). I think you can do this with the WinAPI though.

SetConsoleTextAttribute was the function called I believe, but I don't use the WinAPI myself so I don't know more than that.
Yup, that's the function for it. Here's how I did it (and put it in a custom header file so that I don't have to write this function every time I want to use it).

Also, I am not sure this is the best method of doing this over there...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57

enum Color_t {Gray, White ,DarkRed,Red,DarkBlue, Blue, DarkGreen,Green,DarkCyan,Cyan,DarkMagenta,Magenta,DarkYellow,Yellow, None};

HANDLE Global::hStdout = GetStdHandle(STD_OUTPUT_HANDLE);

void SetColor(Color_t Fore)
{
	WORD fore;

	switch(Fore)
	{
	case 0:
		fore = FOREGROUND_RED|FOREGROUND_BLUE|FOREGROUND_GREEN;
		break;
	case 1:
		fore = FOREGROUND_RED|FOREGROUND_BLUE|FOREGROUND_GREEN|FOREGROUND_INTENSITY;
		break;
	case 2:
		fore = FOREGROUND_RED;
		break;
	case 3:
		fore = FOREGROUND_RED|FOREGROUND_INTENSITY;
		break;
	case 4:
		fore = FOREGROUND_BLUE;
		break;
	case 5:
		fore = FOREGROUND_BLUE|FOREGROUND_INTENSITY;
		break;
	case 6:
		fore = FOREGROUND_GREEN;
		break;
	case 7:
		fore = FOREGROUND_GREEN|FOREGROUND_INTENSITY;
		break;
	case 8:
		fore = FOREGROUND_BLUE|FOREGROUND_GREEN;
		break;
	case 9:
		fore = FOREGROUND_BLUE|FOREGROUND_GREEN|FOREGROUND_INTENSITY;
		break;
	case 10:
		fore =  FOREGROUND_BLUE|FOREGROUND_RED;
		break;
	case 11:
		fore = FOREGROUND_BLUE|FOREGROUND_RED|FOREGROUND_INTENSITY;
		break;
	case 12:
		fore = FOREGROUND_RED|FOREGROUND_GREEN;
		break;
	case 13:
		fore = FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_INTENSITY;
		break;
	}

	SetConsoleTextAttribute(Global::hStdout,fore);
}


Reference:
http://msdn.microsoft.com/en-us/library/ms686047(v=VS.85).aspx


EDIT:
Also about how to use it:
1
2
3
4
SetColor(Blue);
cout << a;
SetColour (Green);
cout << b;

Will set the Colour of a to Blue and of b to green.

You can use any of the 13 colours in the enum (None won't do anything here, so ignoring it is the best option. I had it for another function that serves a similar function.)
Last edited on
Thanks

:D
Topic archived. No new replies allowed.