Saturday, March 19, 2011

changing text color in codeblock

Changing text color in console applications created using the GCC compiler in codeblocks is challenging until an unless you use the graphic library. 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 can use windows.h library function. Here in this article, I will share sample code to change text color. The sample program is written in C using windows.h library function.

#include <windows.h>         //header file for windows
#include <stdio.h>           //C standard library
void SetColor(int ForgC);
int main()
{
    SetColor(34);
    printf("test color");
    return 0;
}
void SetColor(int ForgC)
{
     WORD wColor;
                          //We will need this handle to get the current background attribute
     HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
     CONSOLE_SCREEN_BUFFER_INFO csbi;

                           //We use csbi for the wAttributes word.
     if(GetConsoleScreenBufferInfo(hStdOut, &csbi))
     {
                     //Mask out all but the background attribute, and add in the forgournd color
          wColor = (csbi.wAttributes & 0xF0) + (ForgC & 0x0F);
          SetConsoleTextAttribute(hStdOut, wColor);
     }
     return;
}
you can change your desire text color by passing integer value range 0 up-to 256 in SetColor( ) function.

3 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