Color in a Console Application

If you want to print a message in your Windows console application using a color other than the default, you just need to call the Win32 API function SetConsoleTextAttribute, specifying the handle of the console and the color.

The color is composed of 2 bytes. The first one is the background color, and the second one the foreground color, so you can get all the combinations by looping from hexadecimal value 00 (black background and black foreground) to FF (white background and white foreground).

This simple program prints the first 16 color combinations:

#include <stdio.h>
#include <windows.h>

int main(void)
{
  HANDLE hConsole;
  int k;

  hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
  for (k = 0x00; k <= 0x0F; k += 0x01)
  {
    // change color
    SetConsoleTextAttribute(hConsole, k);
    printf("%2d Colored text in a Windows console\n", k);
  }
  // restore to normal color
  SetConsoleTextAttribute(hConsole, 0x07);

  return 0;
}

Colored text inside a Windows console

Comments