如何获取当前的控制台背景和文本颜色?

rsk*_*k82 10 c++ windows console colors

我知道如何设置它们(SetConsoleTextAttribute)但没有GetConsoleTextAttribute来检索此信息.在未受影响的控制台上,它应该是int 7.

问题是当从设置文本颜色的程序退出时,它在给定窗口运行的时间内保持不变,并且我不能假设用户没有将颜色设置为他的自定义喜好.

Ray*_*hen 8

一个快速的wincon.h演示文稿,CONSOLE_SCREEN_BUFFER_INFOwAttributes成员被记录为 "由WriteFile和WriteConsole函数写入屏幕缓冲区的字符的属性,或者由ReadFile和ReadConsole函数回显到屏幕缓冲区." 这与以下描述SetConsoleTextAttribute匹配:"设置WriteFile或WriteConsole函数写入控制台屏幕缓冲区的字符的属性,或者由ReadFile或ReadConsole函数回显." 结构由返回GetConsoleScreenBufferInfo.


Pio*_*ski 7

感谢Talent25,我做了这个功能:

#include <Windows.h>    
bool GetColor(short &ret){
        CONSOLE_SCREEN_BUFFER_INFO info;
        if (!GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info))
            return false;
        ret = info.wAttributes;
        return true;
}
Run Code Online (Sandbox Code Playgroud)

使用它:

GetColor(CurrentColor);
Run Code Online (Sandbox Code Playgroud)

CurrentColor - 输出颜色数的变量(背景*16 +主色).返回值通知操作是否成功.


小智 5

这是代码片段。

HANDLE                      m_hConsole;
WORD                        m_currentConsoleAttr;
CONSOLE_SCREEN_BUFFER_INFO   csbi;

//retrieve and save the current attributes
m_hConsole=GetStdHandle(STD_OUTPUT_HANDLE);
if(GetConsoleScreenBufferInfo(m_hConsole, &csbi))
    m_currentConsoleAttr = csbi.wAttributes;

//change the attribute to what you like
SetConsoleTextAttribute (
            m_hConsole,
            FOREGROUND_RED |
            FOREGROUND_GREEN);

//set the ttribute to the original one
SetConsoleTextAttribute (
            m_hConsole,
            m_currentConsoleAttr);
Run Code Online (Sandbox Code Playgroud)