Forums

Forums (http://www.abandonia.com/vbullet/index.php)
-   Programming (http://www.abandonia.com/vbullet/forumdisplay.php?f=25)
-   -   C++ text color include for Windows enviroment (http://www.abandonia.com/vbullet/showthread.php?t=24232)

The Fifth Horseman 20-03-2010 01:11 PM

C++ text color include for Windows enviroment
 
1 Attachment(s)
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:
Source code

(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!
Code:

#include <iosfwd>
#include <windows.h>
class colors {
private:
        int val;
        friend std::ostream& operator<< (std::ostream& stream, colors const input) {
                SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 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"
Code:

#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.


The current time is 01:03 AM (GMT)

Powered by vBulletin® Version 3.7.1
Copyright ©2000 - 2025, Jelsoft Enterprises Ltd.