Feb 102009
How to Change Change Console Application Text Color?
To change console application text color use Windows API SetConsoleTextAttribute. This API 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. This function affects text written after the function call.
BOOL WINAPI SetConsoleTextAttribute( _In_ HANDLE hConsoleOutput, _In_ WORD wAttributes );
To determine the current color attributes of a screen buffer, call the GetConsoleScreenBufferInfo function.
Sample Code
Easy! Call SetConsoleTextAttribute function with appropriate color codes as shown below…
#include <windows.h> #include <iostream> using namespace std; // A generic function call to set color for text being output void SetColor( const int Color ) { SetConsoleTextAttribute( GetStdHandle( STD_OUTPUT_HANDLE ), Color ); } int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]) { // Only change foreground color SetColor(FOREGROUND_GREEN | FOREGROUND_INTENSITY); cout << "Visit http://ntcoder.com/bab" << endl; // This time change background color too SetColor(FOREGROUND_BLUE | BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE | FOREGROUND_INTENSITY); cout << "Visit http://ntcoder.com/bab" << endl; return 0; }
INvalid unless you state which compiler and where the prototype for SetConsoleTextAttribute(… is Does not work ‘as-is’ in MS Vis C++ 6
The header file to include will be windows.h
[…] How to change console application text color? « bits and bytes Easy! call SetConsoleTextAttribute function with appropriate color codes as follows… (tags: color c++ GUI consol) […]