Saturday, March 19, 2011

Text background color of console windows using C in code::block


In my earlier article changing text color in codeblocks, I had provided sample source code to change text color using windows.h library function. Similarly, we can also change text background color using windows.h library function. Here, I have shared sample source code to change text background color. The sample program is written in C.

#include <windows.h>
#include <stdio.h>
void SetColorAndBackground(int ForgC, int BackC);
int main()
{
    SetColorAndBackground(5,1);   //color value range 0 up-to 256
    printf("what is text background color");
    Sleep(1000);
    return 0;
}
void SetColorAndBackground(int ForgC, int BackC)
{
     WORD wColor = ((BackC & 0x0F) << 4) + (ForgC & 0x0F);
     SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), wColor);
     return;
}
You can change text background color by passing integer value range 0 up-to 256 in SetColorAndBackground(int ForgC, int BackC) function. First parameter is for text color and second parameter is for background color.

2 comments:

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

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

    ReplyDelete