c ++将控制台文本颜色设置为RGB值 [英] c++ set console text color to RGB value

查看:238
本文介绍了c ++将控制台文本颜色设置为RGB值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将控制台的文本颜色设置为RGB颜色。
我创建了一个函数来获取控制台的ColorTable并更改它的颜色,但它不工作。我不知道如何设置文本颜色为颜色表中的值,所以我只是更改整个颜色表,但它不做任何事情。

I want to set the text color of the console to a RGB color. I created a function to get the ColorTable of the console and change the colors in it, but it doesn't work. I don't know how to set the text color to a value from the color table so I just change the whole color table, but it doesn't do anything.

void setColor(int r, int g, int b)
{
    COLORREF cr;
    cr = RGB(r, g, b);
    PCONSOLE_SCREEN_BUFFER_INFOEX ci;
    CONSOLE_SCREEN_BUFFER_INFOEX cir;
    ci = ○
    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    GetConsoleScreenBufferInfoEx(hConsole , ci);
    cout <<hex<< ci->ColorTable[2];
    for(int i=0;i<16;i++){
            ci->ColorTable[i] = cr;
    }
    SetConsoleScreenBufferInfoEx(hConsole, ci);

    GetConsoleScreenBufferInfoEx(hConsole , ci);

    cout <<endl <<  ci->ColorTable[2];
}

main()我调用函数多次,但输出是相同的每个调用和颜色不变。 SetConsoleScreenBufferInfoEx() GetConsoleScreenBufferInfoEx()似乎没有做任何事情, ci 在调用时保持不变。

In main() I invoke the function multiple times, but the output is the same every call and the color doesn't change. SetConsoleScreenBufferInfoEx() and GetConsoleScreenBufferInfoEx() don't seem to do anything, ci remains unchanged when they are called.

我该怎么办?

如果它工作,我认为背景颜色也会改变,因为我改变整个调色板,所以我如何设置文本颜色从颜色表中的特定值,例如我把 ci-> ColorTable [2] = cr; 放在 changeColor() ,我如何将文本颜色设置为现在存储在 ColorTable [2]

Also, if it worked I assume the background color would also get changed because I change the whole pallette, so how do I set the text color to a specific value from the color table, e.g. i put ci->ColorTable[2] = cr; in the changeColor() function instead of the for loop, how can I set the text color to the color that is now stored in ColorTable[2]?

推荐答案

您需要使用 SetConsoleTextAttribute 设置当前文本颜色和背景颜色,请参阅 http://msdn.microsoft.com/en-us/library/windows/desktop/ ms686047(v = vs.85).aspx 了解详情。

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.

这篇关于c ++将控制台文本颜色设置为RGB值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆