Tuesday 12 February 2013

How to change the text color of console using C

The following code changes the text color of console to the color defined by color value supplied. You must include <windows.h> to use this function. It works on windows only.
#include <stdio.h>
#include <windows.h>
#include <conio.h>
void SetColor(int ForgC)
{
     WORD wColor;
     HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
     CONSOLE_SCREEN_BUFFER_INFO csbi;
     if(GetConsoleScreenBufferInfo(hStdOut, &csbi))
     {
          wColor = (csbi.wAttributes & 0xF0) + (ForgC & 0x0F);
          SetConsoleTextAttribute(hStdOut, wColor);
     }
     return;
}
int main(){
  int fore;
  printf("Enter text color value: ");
  scanf("%d",&fore);
  SetColor(fore);
  printf("Your color will be like this");
  getch();
  return 0;
}

Output

text_color

No comments:

Post a Comment

Comment