5

我想写一些类似的东西

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 领域消失了。

4

2 回答 2

9

您可以使用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在结束时执行重置。

于 2011-10-15T14:35:52.563 回答
1

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

于 2011-10-15T14:29:58.050 回答