2011-12-20 77 views
6

我知道如何設置它們(SetConsoleTextAttribute),但沒有GetConsoleTextAttribute來檢索這些信息。在不受影響的控制檯上,它應該是int 7.如何獲取當前控制檯背景和文本顏色?

問題是,當從設置文本顏色的程序退出時,窗口運行時間保持不變,並且我不能假定用戶沒有設置顏色以他的習慣喜歡。

回答

4

wincon.h快速的grep表明CONSOLE_SCREEN_BUFFER_INFO具有wAttributes構件是documented as「由WriteFile的和WriteConsole功能寫入到屏幕緩衝寄存器,或呼應由ReadFile和ReadConsole功能的畫面緩存器中的字符的屬性。 「這與the description of SetConsoleTextAttribute匹配:「通過WriteFile或WriteConsole函數設置寫入控制檯屏幕緩衝區的字符的屬性,或者由ReadFile或ReadConsole函數響應。」該結構由GetConsoleScreenBufferInfo返回。

2

這裏是代碼片段。

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

希望這有幫助。

6

由於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 +主色)。返回的值通知行動是否成功。