Pages

Saturday, 23 April 2016

Change Console Windows Background Color

Use this source code to change console windows background color in code::block.
Pass integer value range 0 to 256 in ClearConsoleToColors(  x, y) function.


#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 (in this case 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;
}

No comments:

Post a Comment