如何获得当前控制台背景和文本颜色

how to get current console background and text colors?

本文关键字:文本 颜色 背景 控制台 何获得      更新时间:2023-10-16

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

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

wincon.h的快速grep显示CONSOLE_SCREEN_BUFFER_INFO有一个wAttributes成员,其文档记录为"由WriteFile和WriteConsole函数写入屏幕缓冲区的字符属性,或由ReadFile和ReadConsole函数回显到屏幕缓冲区的字符属性"。这与SetConsoleTextAttribute的描述相匹配:"设置由WriteFile或WriteConsole函数写入控制台屏幕缓冲区的字符的属性,或由ReadFile或ReadConsole函数返回。"结构由GetConsoleScreenBufferInfo返回。

感谢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;
}
使用它:

GetColor(CurrentColor);

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

下面是代码片段

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