对从控制台c++应用程序输出到Windows cmd.exe的标准输出进行着色
Colorize stdout output to Windows cmd.exe from console C++ app
我想写一些类似于
的东西cout << "this text is not colorizedn";
setForeground(Color::Red);
cout << "this text shows as redn";
setForeground(Color::Blue);
cout << "this text shows as bluen";
用于在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 colorizedn";
SetConsoleTextAttribute(consolehwnd, FOREGROUND_RED);
cout << "this text shows as redn";
SetConsoleTextAttribute(consolehwnd, FOREGROUND_BLUE);
cout << "this text shows as bluen";
}
此函数影响函数调用后写入的文本。所以最后你可能想要恢复到原来的颜色/属性。您可以使用GetConsoleScreenBufferInfo在最开始记录初始颜色,并在结束时执行w/SetConsoleTextAttribute
的重置。
看看http://gnuwin32.sourceforge.net/packages/ncurses.htm
相关文章:
- 父进程意外被子 cmd 杀死.exe运行 java jar 的进程 - WINDOWS 7 问题 - C++
- cmd.exe与Powershell中C++程序的不同执行时间
- 无法使用QProcess在cmd.exe中执行复制命令
- 如何将我的程序转换为.dll文件并使用rundll32.exe在cmd中运行它?
- 从 CMD 运行.exe并自动向其传递参数
- CMD:程序.exe 1< "A:/input.txt"产生无输出
- 如何循环访问在 cmd 中获取参数的 exe 文件
- CMD.EXE与CreateProcess致电后立即关闭
- 如何在C++程序中打开一个新的cmd.exe并获取其句柄
- 通过 cmd 将参数传递给C++编译的 exe
- 无法读取在cmd.exe管道下启动的进程的输出
- CreateProcess cmd.exe读/写管道死锁
- CreateProcess正在调用cmd.exe,包括没有显示(闪烁)窗口的参数
- 将多个cmd.exe参数/参数传递给Shellexecute(ex)
- cmd.exe打开PDF并打印它
- cmd 命令启动无法与新版本的 mingw32-make.exe一起使用?
- C 向CMD.EXE监视命令注入DLL
- 从.exe输出到 cmd
- C 如何通过同一MFC应用程序通过System Command打开Excel文件后关闭CMD EXE
- CMD.EXE中的控制台输出,通过C 进行powershell.exe