经常看到一些开源软件(例如NDK编译的时候,操作系统启动的时候)打印的输出很多是彩色的,这样比较容易分辨哪些是重点,增强可读性。代码如下: [cpp] view plain copy #include <stdio.h> #include <windows.h> #define LOG_TYPE_NORMAL 0 #define LOG_TYPE_WARNING 1 #define LOG_TYPE_ERROR 2 void LOG(int iLogType, char* szFmt, ...) { va_list argPtr; char szOut[1024*2]; DWORD dwWs; HANDLE hConsoleOutput; CONSOLE_SCREEN_BUFFER_INFO screenBufferInfo; WORD wAttributes; hConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE); GetConsoleScreenBufferInfo(hConsoleOutput, &screenBufferInfo); switch( iLogType ) { case LOG_TYPE_NORMAL: // 一般信息 wAttributes = FOREGROUND_GREEN | FOREGROUND_INTENSITY; break; case LOG_TYPE_WARNING: // 警告信息,黄色 wAttributes = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY; break; case LOG_TYPE_ERROR: // 错误信息,红色 wAttributes = FOREGROUND_RED|FOREGROUND_INTENSITY; break; default: wAttributes = screenBufferInfo.wAttributes; } va_start(argPtr, szFmt); vsprintf(szOut, szFmt, argPtr); va_end(argPtr); SetConsoleTextAttribute(hConsoleOutput, wAttributes); WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), szOut, strlen(szOut), &dwWs, NULL); SetConsoleTextAttribute(hConsoleOutput, screenBufferInfo.wAttributes); } void main() { char *normal = "hello"; int warning = 10; unsigned error = 0x80001000; LOG(LOG_TYPE_NORMAL,"%s\n",normal); LOG(LOG_TYPE_WARNING,"%x\n",warning); LOG(LOG_TYPE_ERROR,"%u\n",error); } 其中黄色的宏是根据光学三原色的红色和绿色或出来的。除了前景颜色,还可以设置背景颜色,具体跟到FORGROUND_RED的定义就可以看到其他类似的参数了。