【问题标题】:Colorize stdout output to Windows cmd.exe from console C++ app从控制台 C++ 应用程序将 stdout 输出着色到 Windows cmd.exe
【发布时间】:2011-12-08 08:50:07
【问题描述】:

我想写一些类似的东西

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()。

标签: c++ windows console-application windows-console


【解决方案1】:

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

【讨论】:

  • 像魅力一样工作。没想到这么简单。
【解决方案2】:

【讨论】:

  • 谢谢,但我正在尝试做一些尽可能少的事情。这是供学生编写的代码,我宁愿让事情变得简单。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-18
  • 2010-12-04
相关资源
最近更新 更多