对从控制台c++应用程序输出到Windows cmd.exe的标准输出进行着色

Colorize stdout output to Windows cmd.exe from console C++ app

本文关键字:exe cmd 标准输出 进行着 Windows 控制台 c++ 应用程序 输出      更新时间:2023-10-16

我想写一些类似于

的东西
cout << "this text is not colorizedn";
setForeground(Color::Red);
cout << "this text shows as redn";
setForeground(Color::Blue);
cout << "this text shows as bluen";

用于在Windows 7下运行的c++控制台程序。我读过全球前景& &;背景可以从cmd.exe的设置更改,或者通过调用system() -但是有什么方法可以在字符级别更改可以编码到程序中的东西吗?起初我认为是"ANSI序列",但它们似乎在Windows舞台上消失了很长时间。

可以使用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 colorizedn";
   SetConsoleTextAttribute(consolehwnd, FOREGROUND_RED);
   cout << "this text shows as redn";
   SetConsoleTextAttribute(consolehwnd, FOREGROUND_BLUE);
   cout << "this text shows as bluen";
}

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

看看http://gnuwin32.sourceforge.net/packages/ncurses.htm