Saturday, August 27, 2011

How to change Background and Foreground color of Console in C

<windows.h> provides various functions to change the properties of windows like changing color, resizing windows, changing cursor position etc. The source code for changing the background and foreground color of console is given below. You can pass different color values to the function to get different color in background and foreground.

#include <stdio.h>
#include <windows.h>
#include <conio.h>
void SetColorAndBackground(int ForgC, int BackC)
{
     WORD wColor = ((BackC & 0x0F) << 4) + (ForgC & 0x0F);;
     SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), wColor);
     return;
}
int main(){
  int fore, back;
  printf("Enter foreground and background color values: ");
  scanf("%d%d",&fore, &back);
  SetColorAndBackground(fore,back);
  printf("Your color will be like this");
  getch();
  return 0;
}

Output


bfcolor

2 comments:

  1. There are 5 errors in your program

    ReplyDelete
    Replies
    1. Hey this program only runs on Windows OS and GNU GCC compiler. It gives errors if run in other platform.

      Delete