在Windows中使用C++进行彩色控制台输出
Color console output with C++ in Windows
有没有办法将彩色文本输出到控制台?我使用的是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";
相关文章:
- C++:将控制台输出存储在宏中更好吗
- OpenCV EqualizeHist()从彩色图像创建黑白图像
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- SSH通过/sbin/SSH无法读取RSA密钥文件(从控制台运行)
- C++控制台应用程序阻止退出
- 如何修复此iFile以将.txt输出到控制台
- 为什么控制台要求输入,即使代码中没有输入
- 彩色图像的卤化物处理平均值
- 在Qt Creator中,如何在连接到正在运行的进程后查看控制台输出
- 控制台输出在 Qt5 中未正确显示
- C++出现控制台错误.我无法识别源代码的问题
- C++程序不会从 Windows 控制台运行
- 有人可以向我解释为什么控制台输出 0 吗?
- Visual Studio 2017 停止工作,并在打开后显示许多控制台窗口
- 如何从 Win32 C++ 应用程序输出到父控制台窗口?
- Win32 API 控制台光标在 WriteConsole 后不移动
- 如何获取控制台窗口的宽度?
- 如何在 Win32 C++控制台应用程序中调用 UWP 类库
- 以原子方式将彩色文本写入 Windows 中的控制台
- 在Windows中使用C++进行彩色控制台输出