繁体   English   中英

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

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

我想写类似的东西

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函数:

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的重置。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM