gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 13:28:50 24 4
gpt4 key购买 nike

我想写类似的东西

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 执行重置。

关于c++ - 从控制台 C++ 应用程序将标准输出着色到 Windows cmd.exe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7778392/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com