Saturday, March 19, 2011

Change text color in C console application

Usually, console applications are black and white. However, sometimes for specific purposes, we need to change the text color to highlight the specific values, dates, or texts. Changing text 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 text color. If you want to change the text color to make console windows colorful then we should use windows.h library function. You can find the sample code below which change text 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 SetColor(int ForgC);
int main(){

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

    return 0;
}

void setColor(int ForgC){

    //We will need this handle to get the current background attribute
    WORD wColor; 
    
    HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
    
    //we use csbi for the wAttributes word.
    CONSOLE_SCREEN_BUFFER_INFO csbi; 

    if(GetConsoleScreenBufferInfo(hStdOut, &csbi)){
        //Mask out all but the background attribute
        //, and add in the foreground color
        wColor = (csbi.wAttributes & 0xF0) + (ForgC & 0x0F);
        SetConsoleTextAttribute(hStdOut, wColor);
    }
    return;
}

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 color by passing integer value range 0 up to 15 in SetColor() function.



4 comments:

  1. I need a help. Please could someone post a code, the classic game of Pong, compiled in Code Blocks in C + +. The game will have to have two players with two goalkeepers, with time and score at the end.

    ReplyDelete
  2. Thanks.Nice code .
    I wanted exactly the same.
    Sudipta Maity,Kolkata

    ReplyDelete
  3. THIS PROGRAM IS FOR C++. CAN YOU SUGGEST ANY PROGRAM TO CHANGE BACKGROUND AND FOREGROUND COLOURS IN C LANGUAGE,ESPECIALLY IN TURBO C/C++ or MINGW ON CODEBLOCKS ?

    ReplyDelete