从控制台C++应用程序将stdout输出着色到Windows cmd.exe

tuc*_*uxi 5 c++ windows console-application windows-console

我想写类似的东西

cout << "this text is not colorized\n";
setForeground(Color::Red);
cout << "this text shows as red\n";
setForeground(Color::Blue);
cout << "this text shows as blue\n";
Run Code Online (Sandbox Code Playgroud)

对于在Windows 7下运行的C++控制台程序,我已经读过可以从cmd.exe的设置或通过调用system()更改全局前景和后台 - 但是有没有办法在字符级别更改可以编码的内容进入一个程序?起初我认为"ANSI序列",但它们似乎在Windows领域长期丢失.

Eri*_*c Z 9

您可以使用SetConsoleTextAttribute函数:

BOOL WINAPI SetConsoleTextAttribute(
  __in  HANDLE hConsoleOutput,
  __in  WORD wAttributes
);
Run Code Online (Sandbox Code Playgroud)

这是一个简短的例子,你可以看看.

#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";
}
Run Code Online (Sandbox Code Playgroud)

此函数影响函数调用后写入的文本.所以最后你可能想要恢复原始的颜色/属性.您可以使用GetConsoleScreenBufferInfo在最开始时记录初始颜色,并SetConsoleTextAttribute在结束时执行重置.