您的位置:首页 > 编程语言 > C语言/C++

Windows下更改C/C++控制台程序文本输出颜色

2009-07-29 09:38 573 查看
保存下面的代码放到一个头文件concol.h中

concol.h

#include <iostream>
using namespace std;
#include <windows.h>

#define RED             0x0004
#define GREEN             0x0002
#define BLUE             0x0001
#define WHITE             RED|GREEN|BLUE
#define YELLOW       RED|GREEN
#define PINK             RED|BLUE
#define TURQUOISE    BLUE|GREEN
#define BG_RED             0x0040
#define BG_GREEN     0x0020
#define BG_BLUE             0x0010
#define BG_WHITE     BG_RED|BG_GREEN|BG_BLUE
#define BG_YELLOW    BG_RED|BG_GREEN
#define BG_PIN       KBG_RED|BG_BLUE
#define BG_TURQUOISE BG_BLUE|BG_GREEN

typedef unsigned short int usint;
//---------------------------------------------------------------------------------
class ostreamHelper
{
private:
usint n_;
bool inten_;
ostream& (*f_)(ostream&,usint,bool);
public:
ostreamHelper(ostream&(*f)(ostream&,usint, bool), usint n, bool inten):f_(f),n_(n),inten_(inten) { }
friend ostream& operator<<(ostream& os,ostreamHelper helper)
{
return helper.f_(os,helper.n_,helper.inten_); }
};
//---------------------------------------------------------------------------------
ostream& ColHelper(ostream& os, usint col, bool inten)
{
HANDLE *hOut=new HANDLE;
*hOut=GetStdHandle(STD_OUTPUT_HANDLE);
if(inten==true)
col+=0x0008;
SetConsoleTextAttribute(*hOut,col);
delete hOut;
return os;
}
//--------------------------------------------------------------------------------
ostreamHelper col(usint col, bool intensiv)
{
return ostreamHelper(&ColHelper,col,intensiv);
}
//---------------------------------------------------------------------------------


下面是测试用例, 包含上面的头文件 concol.h

#include "concol.h"

int main()
{
cout << col(RED,true) << "hi, I'm an intensiv Red :D/n";
cout << "I'm still red, couz u dont change it!/n";
cout << col(YELLOW|BG_GREEN,true) << "hi, I'm yellow and my BG is greeen :D/n";
cout << col(YELLOW,false) << "now, my color is not intensiv :(/n";
cout << col(WHITE,false) << "now I have the standard color. :> great./n";
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: