【问题标题】:How to change text or background color in a Windows console application如何在 Windows 控制台应用程序中更改文本或背景颜色
【发布时间】:2012-01-07 07:41:55
【问题描述】:

哪个 C++ 函数更改文本或背景颜色(MS Visual Studio)?比如cout<<"This text";如何让“This text”变成红色。

【问题讨论】:

标签: c++ text background-color


【解决方案1】:

您可以使用 Win32 更改控制台应用程序的颜色,下面是一个示例,说明如何:

#include "stdafx.h"
#include <Windows.h>
#include <iostream>

using namespace std; 

int main(void) 
{ 
    HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE); 
    if (hStdout == INVALID_HANDLE_VALUE) 
    {
        cout << "Error while getting input handle" << endl;
        return EXIT_FAILURE;
    }
    //sets the color to intense red on blue background
    SetConsoleTextAttribute(hStdout, FOREGROUND_RED | BACKGROUND_BLUE | FOREGROUND_INTENSITY);

    cout << "This is intense red text on blue background" << endl;
    //reverting back to the normal color
    SetConsoleTextAttribute(hStdout, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);

    return EXIT_SUCCESS;
}

查看 SetConsoleTextAttribute 函数和 Console Screen Buffers 的 MSDN 文档了解更多信息。

here 提供了有关使用 Win32 的控制台应用程序的更完整示例。

【讨论】:

  • +1 不错的答案...但我必须注释 #include "stdafx.h" 才能在代码块 ide 上运行此代码。
【解决方案2】:

颜色不是 C++ 的东西,而是 终端 的属性。如果您的终端使用 ANSI(例如,任何 Linux 终端,或 DOS 或 Windows NT,如果您将 DEVICE=C:\DOS\ansi.sys 添加到您的 config.sys,或者更高版本的 Windows,如果您使用 cmd.exe /kansicon 调用 shell),那么您可以尝试以下噱头:

#define ANSI_COLOR_RED     "\x1b[31m"
#define ANSI_COLOR_GREEN   "\x1b[32m"
#define ANSI_COLOR_YELLOW  "\x1b[33m"
#define ANSI_COLOR_BLUE    "\x1b[34m"
#define ANSI_COLOR_MAGENTA "\x1b[35m"
#define ANSI_COLOR_CYAN    "\x1b[36m"

#define ANSI_COLOR_BRIGHT  "\x1b[1m"
#define ANSI_COLOR_RESET   "\x1b[0m"


std::cout << ANSI_COLOR_RED "Hello World\n" ANSI_COLOR_RESET;

维基百科有一个list of ANSI escape sequences

【讨论】:

  • @Kyberias:它在 Windows NT 中对你 load ansi.sys 执行,就像在 DOS 中一样,或者如果你说 cmd.exe /kansicon 则在以后执行。
  • 从 Threshold 2 开始的 Windows 10 原生支持此功能,无需参数。
  • @ildjarn:进步势不可挡!
【解决方案3】:

我相信您正在寻找SetConsoleTextAttribute 函数。第一个参数hConsoleOutput 将是通过GetStdHandle(STD_OUTPUT_HANDLE) 获得的标准输出句柄。第二个参数是所需character attributes 的按位或 (|) 组合。

另见:KB319883 How to change foreground colors and background colors of text in a Console window by using Visual C#

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-29
    • 1970-01-01
    • 1970-01-01
    • 2015-05-01
    • 2020-01-18
    • 1970-01-01
    相关资源
    最近更新 更多