c++ set console text color to RGB value

好久不见. 提交于 2019-12-06 20:56:33

You need to use SetConsoleTextAttribute to set the current text color and background color, see http://msdn.microsoft.com/en-us/library/windows/desktop/ms686047(v=vs.85).aspx for details.

A Windows console color table looks like this:

Color            Background Foreground
---------------------------------------------
Black            0           0
Blue             1           1
Green            2           2
Cyan             3           3
Red                  4           4
Magenta          5           5
Brown            6           6
White            7           7
Gray             -           8
Intense Blue     -           9
Intense Green    -           10
Intense Cyan     -           11
Intense Red          -           12
Intense Magenta  -           13
Yellow           -           14
Intense White    -               15

To set background colors you have to combine the foreground color code with the background color code using this equation:

finalcolor = (16*backgroundcolor) + foregroundcolor

if you want to set a text color that has a blue background and white text you simply look up the color code in the table. Blue is 1 and white is 15;

Hence int backgroundcolor=1; and int foregroundcolor=15;

#include <windows.h>
#include <iostream> 
using namespace std;

void setcolor(int color)
{
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),color);
    return;
}

int main()
{

    int foregroundcolor=15;
    int backgroundcolor=1;
    int finalcolor;

    finalcolor=(16*backgroundcolor)+foregroundcolor;

    setcolor(finalcolor);
    cout<<"finalcolor=(16*backgroundcolor)+foregroundcolor\n";
    setcolor(7);

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