C++ creating a change console colors function

╄→гoц情女王★ 提交于 2019-12-25 02:23:28

问题


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 );

This will be a function to allow user input to change the console colors. I know for a fact this works for windows, but I'm not sure what it would do on a linux machine. unfortunately I don't know how to compose the string colors including the characters in the string that goes into the console attribute function. Using this method I get this error...

error: cannot convert 'std::string' to 'WORD' for argument '2' to 'BOOL SetConsoleTextAttribute(void*, WORD)'

Any ideas? Any better ways that I can change the colors? I know of windows system calls, but I thought this may or may not work on linux. Possibly I could make two different calls and one for linux, but that sounds too complicated and I wouldn't know how to make the program tell the difference.


回答1:


As noted, the function takes a WORD value. In essence, there are defined constants of Red, Green, and Blue values for background and foreground colors that can be mixed together to create other colors. An example piece of code from this site:

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;
}

The site also lists some other combinations that can be used.



来源:https://stackoverflow.com/questions/5958894/c-creating-a-change-console-colors-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!