Saturday, March 19, 2011

Change console windows background color in C

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

#include <windows.h>          //header file for windows
#include <stdio.h>

void ClearConsoleToColors(int ForgC, int BackC);
int main()
{
    ClearConsoleToColors(0,1);
    Sleep(1000);
    return 0;
}
void ClearConsoleToColors(int ForgC, int BackC)
{
    WORD wColor = ((BackC & 0x0F) << 4) + (ForgC & 0x0F);
    //Get the handle to the current output buffer...
    HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
    //This is used to reset the carat/cursor to the top left.
    COORD coord = {0, 0};
    //A return value... indicating how many chars were written
    //   not used but we need to capture this since it will be
    //   written anyway (passing NULL causes an access violation).
    DWORD count;

    //This is a structure containing all of the console info
    // it is used here to find the size of the console.
    CONSOLE_SCREEN_BUFFER_INFO csbi;
    //Here we will set the current color
    SetConsoleTextAttribute(hStdOut, wColor);
    if(GetConsoleScreenBufferInfo(hStdOut, &csbi))
    {
        //This fills the buffer with a given character (e.g 32=space).
        FillConsoleOutputCharacter(hStdOut, (TCHAR) 32
        , csbi.dwSize.X * csbi.dwSize.Y, coord, &count);

        FillConsoleOutputAttribute(hStdOut, csbi.wAttributes
        , csbi.dwSize.X * csbi.dwSize.Y, coord, &count );
        //This will set our cursor position for the next print statement.
        SetConsoleCursorPosition(hStdOut, coord);
    }
    return;
}
You can change console windows background color by passing integer value range 0 up-to 256 in ClearConsoleToColors(int ForgC, int BackC) function.



3 comments:

  1. Thanks. The code works. I've been finding it.

    ReplyDelete
  2. lel dis code hav no sweg

    ReplyDelete
  3. can u please tell me how to make a library or header file of this so that i can simply use it?

    ReplyDelete