您可以使用SetConsoleTextAttribute函数:
BOOL WINAPI SetConsoleTextAttribute(
__in HANDLE hConsoleOutput,
__in WORD wAttributes
);
这是一个简短的示例,您可以看一下。
#include "stdafx.h"
#include <iostream>
#include <windows.h>
#include <winnt.h>
#include <stdio.h>
using namespace std;
int main(int argc, char* argv[])
{
HANDLE consolehwnd = GetStdHandle(STD_OUTPUT_HANDLE);
cout << "this text is not colorized\n";
SetConsoleTextAttribute(consolehwnd, FOREGROUND_RED);
cout << "this text shows as red\n";
SetConsoleTextAttribute(consolehwnd, FOREGROUND_BLUE);
cout << "this text shows as blue\n";
}
此函数影响函数调用后写入的文本。所以最后你可能想恢复到原来的颜色/属性。您可以使用GetConsoleScreenBufferInfo在开始时记录初始颜色并SetConsoleTextAttribute
在结束时执行重置。