从控制台C ++应用程序着色到Windows cmd.exe的stdout输出 [英] Colorize stdout output to Windows cmd.exe from console C++ app

查看:166
本文介绍了从控制台C ++应用程序着色到Windows cmd.exe的stdout输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个类似于

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

for a C++ console program running under Windows 7. I have read that global foreground & background can be changed from cmd.exe's settings, or by calling system() - but is there any way to change things at character-level that can be coded into a program? At first I thought "ANSI sequences", but they seem to be long lost in the Windows arena.

推荐答案

a href =http://msdn.microsoft.com/en-us/library/windows/desktop/ms686047%28v=vs.85%29.aspx> SetConsoleTextAttribute 功能:

You can use SetConsoleTextAttribute function:

BOOL WINAPI SetConsoleTextAttribute(
  __in  HANDLE hConsoleOutput,
  __in  WORD wAttributes
);

这里有一个简单的例子,你可以看看。

Here's a brief example which you can take a look.

#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 记录初始颜色,并在结束时执行重置w / SetConsoleTextAttribute

This function affects text written after the function call. So finally you probably want to restore to the original color/attributes. You can use GetConsoleScreenBufferInfo to record the initial color at the very beginning and perform a reset w/ SetConsoleTextAttribute at the end.

这篇关于从控制台C ++应用程序着色到Windows cmd.exe的stdout输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆