How to get current background colors and console text?

I know how to install them (SetConsoleTextAttribute), but there is no GetConsoleTextAttribute to get this information. On an unaffected console, this should be int 7.

The problem is that when you exit the program that sets the color of the text, it remains unchanged for the time it takes for this window to start, and I cannot assume that the user did not set the color to his liking.

+10
source share
3 answers

The quick output of wincon.h shows that CONSOLE_SCREEN_BUFFER_INFO has a member wAttributes , which is documented as “Attributes of characters written to the screen buffer by the WriteFile and WriteConsole functions, or reflected into the screen buffer by the ReadFile and ReadConsole functions.” This corresponds to the description of the SetConsoleTextAttribute : “Sets written to the buffer on the console screen using the WriteFile or WriteConsole function or reflected by the ReadFile or ReadConsole function. " The structure is returned by GetConsoleScreenBufferInfo .

+8
source

Thanks to Talent25, I made this function:

 #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; } 

using it:

 GetColor(CurrentColor); 

CurrentColor is a variable for the output color number (background * 16 + primary color). The return value indicates that the action was successful.

+7
source

Here is a snippet of code.

 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); 
+5
source

Source: https://habr.com/ru/post/904171/


All Articles