C++ Console Color

email me

How to write C++ console applications that print colored text?

Method 1

#include <iostream>
#include <windows.h>

int main()
{
const WORD colors[] =
{
0x1A, 0x2B, 0x3C, 0x4D, 0x5E, 0x6F,
0xA1, 0xB2, 0xC3, 0xD4, 0xE5, 0xF6
};

HANDLE hstdin = GetStdHandle( STD_INPUT_HANDLE );
HANDLE hstdout = GetStdHandle( STD_OUTPUT_HANDLE );
WORD index = 0;

// Remember how things were when we started
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo( hstdout, &csbi );

// Tell the user how to stop
SetConsoleTextAttribute( hstdout, 0xEC );
std::cout << "Press any key to quit.\n";

// Draw pretty colors until the user presses any key
while (WaitForSingleObject( hstdin, 100 ) == WAIT_TIMEOUT)
{
SetConsoleTextAttribute( hstdout, colors[ index ] );
std::cout << "\t\t\t\t Hello World \t\t\t\t" << std::endl; if (++index > sizeof(colors)/sizeof(colors[0]))
index = 0;
}
FlushConsoleInputBuffer( hstdin );

// Keep users happy
SetConsoleTextAttribute( hstdout, csbi.wAttributes );
return 0;
}

//bit 0 - foreground blue
//bit 1 - foreground green
//bit 2 - foreground red
//bit 3 - foreground intensity
//bit 4 - background blue
//bit 5 - background green
//bit 6 - background red
//bit 7 - background intensity



Method 2

#include <iostream>

int main()
{
while(true)
{
system("Color 1A");
std::cout << "\t\t\t Hello World" << std::endl;
system("Color 2B");
std::cout << "\t\t\t Hello World" << std::endl;
system("Color 3C");
std::cout << "\t\t\t Hello World" << std::endl;
system("Color 4D");
std::cout << "\t\t\t Hello World" << std::endl;
system("Color 5E");
std::cout << "\t\t\t Hello World" << std::endl;
system("Color 6F");
std::cout << "\t\t\t Hello World" << std::endl;
system("Color A1");
std::cout << "\t\t\t Hello World" << std::endl;
system("Color B2");
std::cout << "\t\t\t Hello World" << std::endl;
system("Color C3");
std::cout << "\t\t\t Hello World" << std::endl;
system("Color D4");
std::cout << "\t\t\t Hello World" << std::endl;
system("Color E5");
std::cout << "\t\t\t Hello World" << std::endl;
system("Color F6");
std::cout << "\t\t\t Hello World" << std::endl;
}
return 0;
}