Win32命令行应用程序是可以加颜色的,使用SetConsoleTextAttribute就可以实现了,记得前年小学期做的程序作业就用了它。
这篇文章很简单,你可以当作是一个cout <<运算符重载的一个简单例子。本文章来源与这里,我只是做一个很不专业解释。
本文章提供的库可以如下使用,上面是显示效果,想起小时候玩的Mud了吧。
#include "ConsoleColor.h"
std::cout << green << "This text is written in green" << white << std::endl;
std::cout << color(FOREGROUND_RED|FOREGROUND_GREEN) << "This text has a really exiting color !"
<< white << std::endl;
ConsoleColor.h的内容
#pragma once
#include <iostream>
#include <windows.h>
inline std::ostream& blue(std::ostream &s)
{
HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hStdout, FOREGROUND_BLUE
|FOREGROUND_GREEN|FOREGROUND_INTENSITY);
return s;
}
inline std::ostream& red(std::ostream &s)
{
HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hStdout,
FOREGROUND_RED|FOREGROUND_INTENSITY);
return s;
}
inline std::ostream& green(std::ostream &s)
{
HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hStdout,
FOREGROUND_GREEN|FOREGROUND_INTENSITY);
return s;
}
inline std::ostream& yellow(std::ostream &s)
{
HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hStdout,
FOREGROUND_GREEN|FOREGROUND_RED|FOREGROUND_INTENSITY);
return s;
}
inline std::ostream& white(std::ostream &s)
{
HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hStdout,
FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_BLUE);
return s;
}//以上这些函数定义本身就是cout的<<操作符的一种参数重载形式,即:
//basic_ostream& operator<<( basic_ostream& (*_Pfn)(basic_ostream&) );
struct color {
color(WORD attribute):m_color(attribute){};
WORD m_color;
};
template <class _Elem, class _Traits>
std::basic_ostream<_Elem,_Traits>&
operator<<(std::basic_ostream<_Elem,_Traits>& i, color& c)
{
HANDLE hStdout=GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hStdout,c.m_color);
return i;
}
最后这个是对于<<操作符的重载,形式类似于如下
template<class _Tr>
basic_ostream<char, _Tr>& operator<<(
basic_ostream<char, _Tr>& _Ostr,
const unsigned char *_Str);
OK,发挥你的想象力,让c++变得更有趣吧。
参考链接: