在Windows中使用C++进行彩色控制台输出

Color console output with C++ in Windows

本文关键字:彩色 控制台 输出 C++ Windows      更新时间:2023-10-16

有没有办法将彩色文本输出到控制台?我使用的是Visual Studio 2010,只需要这些代码就可以在Windows中工作。

除了windows COLOR命令,我一直没有找到任何东西,但它改变了整个屏幕的颜色,我正在寻找只会改变我希望输出的部分的东西。我在托管C++中看到过

例如,

{color red}
cout << "Hello ";
{color blue}
cout << "worldn";

会产生红色和蓝色的"你好世界"。

我从这里获得了以下代码:

// color your text in Windows console mode
// colors are 0=black 1=blue 2=green and so on to 15=white
// colorattribute = foreground + background * 16
// to get red text on yellow use 4 + 14*16 = 228
// light red on yellow would be 12 + 14*16 = 236
// a Dev-C++ tested console application by vegaseat 07nov2004
#include <iostream>
#include <windows.h> // WinApi header
using namespace std; // std::cout, std::cin
int main()
{
HANDLE hConsole;
int k;
hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
// you can loop k higher to see more color choices
for(k = 1; k < 255; k++)
{
// pick the colorattribute k you want
SetConsoleTextAttribute(hConsole, k);
cout << k << " I want to be nice today!" << endl;
}
cin.get(); // wait
return 0;
}

在Windows中为C++输出着色是通过SetConsoleTextAttribute完成的,其中控制台的HANDLE与属性一起传入。但是,调用SetConsoleTextAttribute很麻烦。幸运的是,互联网和github上有很多小库可以提供帮助,你应该选择一个你喜欢的API。如果要使用运算符<lt;,我推荐这个仅表头的库https://github.com/ikalnitsky/termcolor.api如下所示:

using namespace termcolor;
std::cout << grey    << "grey message"    << reset << std::endl;
std::cout << red     << "red message"     << reset << std::endl;

如果必须重新设置颜色会让你感到厌烦,那就试试我的库。它也是头文件,仅限Windows,它可以让您轻松地为printf语句着色:https://github.com/jrebacz/colorwin.api如下所示:

using namepsace wincolor;
std::cout << color(gray) << "grey messagen";
std::cout << color(red) << "red messagen";
std::cout << "normal colorn";
{
    withcolor scoped(red);
    std::cout << "|redn";
    std::cout << "|red againn";
}
std::cout << "normal colorn";
withcolor(cyan).printf("A cyan printf of %dn", 1234);

这是我们的内部解决方案:

inline void setcolor(int textcol, int backcol)
{
    if ((textcol % 16) == (backcol % 16))textcol++;
    textcol %= 16; backcol %= 16;
    unsigned short wAttributes = ((unsigned)backcol << 4) | (unsigned)textcol;
    HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
    CONSOLE_SCREEN_BUFFER_INFO csbi;
    SetConsoleTextAttribute(hStdOut, wAttributes);
}

以下是可供选择的颜色示例:

#define LOG_COLOR_WHITE 7
#define COLOR_GREEN 10
#define COLOR_YELLOW 14 
#define COLOR_MAGENTA 13

您可以使用system(")命令,其使用方式如下:

cout<<"lol";
system("color 1") // the colours are from 1 to 15. 
cout<<"Coloured text! yay";