Reputation: 29377
I know how to set them (SetConsoleTextAttribute) but there isn't a GetConsoleTextAttribute to retrieve this information. On a unaffected console it should be int 7.
The problem is that when exiting from a program that sets the text color it stays the same for the time given window runs, and I cannot assume that user hasn't set the colors to his custom liking.
Upvotes: 19
Views: 10785
Reputation: 99
Here is code snippet.
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);
Upvotes: 8
Reputation: 419
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 - variable for output number of color (background * 16 + main color). Returned value informs if action was successful.
Upvotes: 11
Reputation: 45173
A quick grep of wincon.h
shows that CONSOLE_SCREEN_BUFFER_INFO
has a wAttributes
member which is documented as "The attributes of the characters written to a screen buffer by the WriteFile and WriteConsole functions, or echoed to a screen buffer by the ReadFile and ReadConsole functions." This matches the description of SetConsoleTextAttribute
: "Sets the attributes of characters written to the console screen buffer by the WriteFile or WriteConsole function, or echoed by the ReadFile or ReadConsole function." The structure is returned by GetConsoleScreenBufferInfo
.
Upvotes: 14