簡體   English   中英

如何獲取當前的控制台背景和文本顏色?

[英]how to get current console background and text colors?

我知道如何設置它們(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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM