Log in

View Full Version : C++ text color include for Windows enviroment


The Fifth Horseman
20-03-2010, 01:11 PM
I was messing with some things yesterday and got somewhat annoyed at the fact that while there is a way to change text and background color in a Windows console enviroment (for specific parts of the text rather than the whole thing at once), it's slightly unintuitive for the end user.

So, I cooked up a custom include with a few functions and definitions that make the color-changing a breeze:
#include <windows.h>
#define BLACK 0
#define BLUE 1
#define GREEN 2
#define CYAN 3
#define RED 4
#define MAGENTA 5
#define BROWN 6
#define LIGHT_GREY 7
#define DARK_GREY 8
#define LIGHT_BLUE 9
#define LIGHT_GREEN 10
#define LIGHT_CYAN 11
#define LIGHT_RED 12
#define LIGHT_MAGENTA 13
#define YELLOW 14
#define WHITE 15
int ____text_color____=7, ____back_color____=0;

void ____recolor() { SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HA NDLE), 16 * ____back_color____ + ____text_color____);
return; }

void colors(int a) { if (a<0) a=7; else if (a>255) { a%=256; }
____back_color____=a/16;
____text_color____=a%16;
____recolor();
return; }

void colors(int a, int b) { if (a<0) { a=0; } else if (a>15) { a%=16; }
if (b<0) { b=7; } else if (b>15) { b%=16; }
____back_color____=a;
____text_color____=b;
____recolor();
return; }

void backcolor(int a) { if (a<0) { a=0; } else if (a>15) { a%=16; }
____back_color____=a;
____recolor();
return; }

void textcolor(int b) { if (b<0) { b=7; } else if (b>15) { b%=16; }
____text_color____=b;
____recolor();
return; }


(Attached as textcolor.h )
Note that negative argument values are used to reset the setting to default.

Peter
14-04-2010, 06:53 PM
Some incomplete attempt to make it into a iomanipulator, didn't try if it compiles on Windows as I wrote it on Linux. Use it only with std::cout!

#include <iosfwd>
#include <windows.h>
class colors {
private:
int val;
friend std::ostream& operator<< (std::ostream& stream, colors const input) {
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HA NDLE), input.val);
return stream;
}
public:
colors(int a) {
val = a < 0 ? 7 : (a % 256);
}
colors (int a, int b) {
a = a < 0 ? 0 : (a % 16);
b = b < 0 ? 7 : (b % 16);
val = a * 16 + b;
}
enum { BLACK,BLUE,GREEN,CYAN,RED };
};

and a tiny example that uses it.
Put directly below the above "header"

#include <iostream>
int main () {
std::cout << "test " << colors(257)<< "test2" << colors(colors::BLUE,10) << "test3" << std::endl;
return 0;
}

You can implement manipulators in even shorter ways, but this one is pretty clean.