最近写的一个程序需要在 Console 窗口中输出大量的信息。大量的信息混在一起看着实在是费劲。因此就想到不同的信息用不同的颜色来输出。
上网查了一番, win32 API 中有一个函数 SetConsoleTextAttribute 可以做这个事。为了用着方便,将这个函数简答的封装了一下。
下面是代码:
#include <Windows.h>
enum ConsoleTextColor{CTC_RED = FOREGROUND_INTENSITY | FOREGROUND_RED,
CTC_GREEN = FOREGROUND_INTENSITY | FOREGROUND_GREEN,
CTC_BLUE = FOREGROUND_INTENSITY | FOREGROUND_BLUE,
CTC_YELLOW = FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN,
CTC_PURPLE = FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_BLUE,
CTC_CYAN = FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_BLUE,
CTC_WHITE = FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE,
CTC_BLACK = 0};
enum ConsoleBackGroundColor{CBC_RED = BACKGROUND_INTENSITY | BACKGROUND_RED,
CBC_GREEN = BACKGROUND_INTENSITY | BACKGROUND_GREEN,
CBC_BLUE = BACKGROUND_INTENSITY | BACKGROUND_BLUE,
CBC_YELLOW = BACKGROUND_INTENSITY | BACKGROUND_RED | BACKGROUND_GREEN,
CBC_PURPLE = BACKGROUND_INTENSITY | BACKGROUND_RED | BACKGROUND_BLUE,
CBC_CYAN = BACKGROUND_INTENSITY | BACKGROUND_GREEN | BACKGROUND_BLUE,
CBC_WHITE = BACKGROUND_INTENSITY | BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE,
CBC_BLACK = 0};
void setConsoleColor(ConsoleTextColor textColor = CTC_WHITE, ConsoleBackGroundColor backgroundColor = CBC_BLACK)
{
//STD_ERROR_HANDLE;
HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(handle, textColor | backgroundColor);
}