Saturday, March 19, 2011

Change text background color in C console application

Usually, console applications are black and white. However, sometimes for specific purposes, we may need to change the text background color to highlight the specific texts. Changing text background color in the console is challenging especially if you are using Codeblocks MinGW. Unlike turbo c/c++ GCC does not provide the function to change the text background color. If you want to change the text background color then we should use windows.h library function. You can find the sample code below which change text background color. The sample program is written in C utilizing windows.h library function.

#include <windows.h>         //header file for windows
#include <stdio.h>           //C standard library
void SetBackgroundColor(int BackC);
int main(){

    int i=0;
    for(i=0; i<256; i++){
        printf("Test Text Background Color for value i: %d\n",i);

    return 0;
void SetBackgroundColor(int BackC)
     WORD wColor = ((BackC & 0x0F) << 4) + (csbi.wAttributes & 0x0F);
     SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), wColor);
In output program, for every 16 values (0-15, 16-32, etc) text colors will repeat. It means in this method we get only 4 bit color space i.e only 16 colors. You can change your desired text background color by passing integer value range 0 up to 15 in SetBackgroundColor() function.


  1. Finally, code involving colours that actually works! And not for Borland compilers. Thank you so much.

  2. how can i copy this code directly and paste into turbo c ??
    because it cant paste over there