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
   cout << "Visit http://ntcoder.com/bab" << endl;

   // This time change background color too
   cout << "Visit http://ntcoder.com/bab" << endl;

   return 0;


Change console application text color. SetConsoleTextAttribute output

Feb 062009

For this purpose we use _kbhit function included in conio.h file. Please note that conio.h is a non-standard header file so can’t say if _kbhit will be available in other libraries. The purpose of  _kbhit is to check whether a key has been hit and so then we can use this function to wait till a key is pressed. To know which key is pressed we can use _getch or _getche functions immediately after a call to _kbhit. _kbhit returns TRUE if a key is pressed else returns FALSE.

Internally _kbhit used PeekConsoleInput windows console API to check whethere is a KEY_EVENT in input queue. If there is one then it returns TRUE. Note that _kbhit peeks on all events from input queue to check whether there is a KEY_EVENT. Note that extended keys are ignored!

Here are some functions to demonstrate the power of _kbhit

  1. ClearInputBuffer – Clears key events from input buffer using _kbhit
  2. Pause – Much like window’s ‘Pause’ command, except for the animation of ellipses.


void ClearInputBuffer()
   while( _kbhit() )
      // Read and ignore chars from input buffer resulting in removal from input buffer

void Pause( const char* Msg = NULL )
   std::cout << ( Msg ? Msg : "Press a key to continue" );    const int EllipsesCount = 3;    const char* MoveBackChars[EllipsesCount] = { "\b", "\b\b", "\b\b\b" };    const char* AllClearText[EllipsesCount] = { " ", "  ", "   " };    const char* Ellipses[EllipsesCount] = { ".", "..", "..." };    int ActiveEllipsesIndex = 0;    while( true )// Animate until a key is pressed    {       std::cout << Ellipses[ActiveEllipsesIndex];       Sleep( 500 );       if( !_kbhit() )       {          std::cout << MoveBackChars[ActiveEllipsesIndex];          std::cout << AllClearText[ActiveEllipsesIndex];          std::cout << MoveBackChars[ActiveEllipsesIndex];       }       else       {          _getch();          break;       }       ActiveEllipsesIndex = (ActiveEllipsesIndex + 1) % EllipsesCount;    } } int main( void ) {    ClearInputBuffer();    Pause();    return 0; }[/sourcecode]

Aug 132008

Ever seen that white progress bar in Windows 2000 while it loads and that spinning stick while Linux is being installed. Out of my curiosity I wrote some functions which emulates these progress bars.

You can optimize/customize these functions for your needs, a thank you message will do the trick with me! Take a look at the screen shot in the end to understand the whole behavior.


int main()
SetConsoleTitle( “Progress messages demo!” );

// First Linux style progress message
void LinuxStyleProgressMessage( const char* Msg );
LinuxStyleProgressMessage( “This is a linux style progress message…” );

// Read in read character from stream to avoid _kbhit from exiting

// Now it’s the turn for Windows 2000 style progress message
std::cout < < "\n\n\nA Windows 2000 style progress message\n\n"; void Windows2000StyleProgressMessage( const char* Msg ); Windows2000StyleProgressMessage( "Installing Windows Vista...\n" ); return 0; } void LinuxStyleProgressMessage( const char* Msg ) { std::cout << Msg; HANDLE hOutputHandle = GetStdHandle( STD_OUTPUT_HANDLE ); CONSOLE_SCREEN_BUFFER_INFO ScrBuffInfo = { 0 }; GetConsoleScreenBufferInfo( hOutputHandle, &ScrBuffInfo ); const char Sticks[] = { '\\',char(179),'/',char(196) }; int Index = 0; while( !_kbhit() ) { std::cout << Sticks[Index]; ++Index; Index %= sizeof(Sticks); Sleep(100); SetConsoleCursorPosition(hOutputHandle,ScrBuffInfo.dwCursorPosition); }// End while }// LinuxStyleProgressMessage void Windows2000StyleProgressMessage( const char* Msg ) { std::cout << Msg; HANDLE hOutputHandle = GetStdHandle( STD_OUTPUT_HANDLE ); CONSOLE_SCREEN_BUFFER_INFO ProgressPos = { 0 }; GetConsoleScreenBufferInfo( hOutputHandle, &ProgressPos ); CONSOLE_SCREEN_BUFFER_INFO MsgPos = ProgressPos; int PercentComplete = 0; int MsgLength = 0; while( !_kbhit() ) { SetConsoleCursorPosition( hOutputHandle, ProgressPos.dwCursorPosition ); for( int MsgIndex = 0; MsgIndex < MsgLength; ++MsgIndex ) { // Insert spaces to delete previous "percentage complete message" std::cout << " "; } SetConsoleCursorPosition( hOutputHandle, ProgressPos.dwCursorPosition ); std::cout << char( 219 ); GetConsoleScreenBufferInfo( hOutputHandle, &ProgressPos ); std::stringstream sstream; sstream << " " << PercentComplete++ << "%"; MsgLength = (int)sstream.str().length(); std::cout << sstream.str(); GetConsoleScreenBufferInfo( hOutputHandle, &MsgPos ); Sleep( rand() % 1000 ); }// End while }// End ShowWin2000StyleProgress[/sourcecode] Here is a snapshot of how this will look, it's not animated but anyway you will have an idea as to what will happen. The stick at the end of the first message keeps rotating. 😉 Of course you can develop different of variations for this.  Second one looks like the progress bar in Windows 2000. As it loads it shows a progress bar kind of thing. It's a non-printable ascii character 219! [caption id="attachment_951" align="alignnone" width="393" caption="A console progress bar demo"]Console progress bars demo[/caption]

Have fun guys! 😉