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

6

我想写一些类似的内容:

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";

我有一个在Windows 7下运行的C++控制台程序。我已经了解到可以从cmd.exe的设置或通过调用system()来更改全局前景色和背景色,但是否有任何方法可以在字符级别上编码进程序来更改这些内容呢?起初我想到了" ANSI序列",但在Windows平台上似乎已经失传了。


使用SetConsoleTextAttribute()函数。 - Hans Passant
2个回答

11

您可以使用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进行重置。


运行得非常好。我不知道它如此简单。 - tucuxi

1

谢谢,但我想尽可能做到最小化。这是给学生用的代码,我宁愿保持事情真正简单。 - tucuxi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接