【问题标题】:C++ creating a change console colors functionC ++创建更改控制台颜色功能
【发布时间】:2011-08-22 23:12:47
【问题描述】:
cout << "Picks your colors..." << endl << "0 = black\t 1 = blue\t 2 = pea green\t 3 = teal\t 4 = red" << endl;
cout << "5 = purple\t 6 = green/brown\t 7 = light grey\t 8 = gark grey" << endl;
cout << "9 = lisghter brighter blue\t A = lime green\t B = light blue/aqua-ish\t C = red/orange" << endl;
cout << "D = pink/rose\t E = yellow" << endl;
char bg;
char fg;
cout << "Pick your foreground:\t";
cin >> fg;
cout << "Pick your background:\t";
cin >> bg;
string colors;
colors = "0x",bg,fg;
SetConsoleTextAttribute( hstdout, colors );

这将是一个允许用户输入更改控制台颜色的功能。我知道这适用于 Windows,但我不确定它会在 linux 机器上做什么。不幸的是,我不知道如何编写字符串颜色,包括进入控制台属性函数的字符串中的字符。使用这种方法我得到这个错误......

错误:无法将 'std::string' 转换为 'WORD' 以将参数 '2' 转换为 'BOOL SetConsoleTextAttribute(void*, WORD)'

有什么想法吗?有什么更好的方法可以改变颜色吗?我知道 Windows 系统调用,但我认为这可能适用于 Linux,也可能不适用于 Linux。可能我可以进行两个不同的调用,一个用于 linux,但这听起来太复杂了,我不知道如何让程序分辨出来。

【问题讨论】:

    标签: c++ colors console


    【解决方案1】:

    如前所述,该函数采用 WORD 值。本质上,背景色和前景色定义了红色、绿色和蓝色值的常量,可以将它们混合在一起以创建其他颜色。本站的一段代码示例:

    http://www.adrianxw.dk/SoftwareSite/Consoles/Consoles4.html

    #include <windows.h>
    #include <iostream>
    using namespace std;
    
    int main()
    {
      HANDLE hOut;
    
      hOut = GetStdHandle(STD_OUTPUT_HANDLE);
    
      SetConsoleTextAttribute(hOut,
                            BACKGROUND_GREEN |
                            BACKGROUND_RED |
                            FOREGROUND_GREEN | 
                            FOREGROUND_BLUE |
                            FOREGROUND_INTENSITY);
      cout << "Intense Cyan on yellow background." << endl;
    
      return 0;
    }
    

    该网站还列出了一些其他可以使用的组合。

    【讨论】:

      猜你喜欢
      • 2013-06-27
      • 1970-01-01
      • 2020-10-06
      • 1970-01-01
      • 2011-09-21
      • 2016-03-04
      • 2015-05-01
      • 2013-06-12
      • 2011-08-11
      相关资源
      最近更新 更多