需要包含 Windows.h 头文件,通过 GetStdHandle 获取输出句柄,来控制输出。
HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(handle, 实际值);
#define FOREGROUND_BLUE 0x0001 // text color contains blue.
#define FOREGROUND_GREEN 0x0002 // text color contains green.
#define FOREGROUND_RED 0x0004 // text color contains red.
#define FOREGROUND_INTENSITY 0x0008 // text color is intensified.
#define BACKGROUND_BLUE 0x0010 // background color contains blue.
#define BACKGROUND_GREEN 0x0020 // background color contains green.
#define BACKGROUND_RED 0x0040 // background color contains red.
#define BACKGROUND_INTENSITY 0x0080 // background color is intensified.
可以多个组合,一个字节的位控制,高四位为背景色控制,第四位为字符颜色控制。XXX_INTENSITY 会增强显示强度。如
FOREGROUND_BLUE | FOREGROUND_INTENSITY | BACKGROUND_RED 字符为高亮蓝色,背景为非高亮红色
即后三位为颜色控制,都选择则为白色,若只选择 强度则为灰色
#include <cstdio>
#include "Windows.h"
int main(int argc, char* argv[])
{
printf("这是默认\n");
HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(handle, FOREGROUND_INTENSITY | FOREGROUND_RED);
printf("这是红色\n");
SetConsoleTextAttribute(handle, FOREGROUND_INTENSITY);
printf("这是灰色\n");
SetConsoleTextAttribute(handle, 0x0f);
printf("这是全部高亮\n");
SetConsoleTextAttribute(handle, 0x07);
printf("这是全部正常\n");
return 0;
}