【问题标题】:how to get current console background and text colors?如何获取当前控制台背景和文本颜色?
【发布时间】:2012-01-24 14:54:04
【问题描述】:

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

问题是当退出一个设置文本颜色的程序时,它在给定窗口运行的时间内保持不变,我不能假设用户没有根据自己的喜好设置颜色。

【问题讨论】:

    标签: c++ windows colors console


    【解决方案1】:

    wincon.h 的快速 grep 显示 CONSOLE_SCREEN_BUFFER_INFO 有一个 wAttributes 成员 documented as "由 WriteFile 和 WriteConsole 函数写入屏幕缓冲区或回显到屏幕缓冲区的字符的属性通过 ReadFile 和 ReadConsole 函数。”这与 the description of SetConsoleTextAttribute 匹配:“设置由 WriteFile 或 WriteConsole 函数写入控制台屏幕缓冲区或由 ReadFile 或 ReadConsole 函数回显的字符的属性。”该结构由GetConsoleScreenBufferInfo 返回。

    【讨论】:

      【解决方案2】:

      感谢 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 + 主色)。返回值通知操作是否成功。

      【讨论】:

        【解决方案3】:

        这里是代码 sn-p。

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-10-29
          • 2020-04-21
          • 2015-11-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多