Saturday, 25 May 2013

Change Console Text and Background Colours (A Stolen Colour Function)

About a week back I copied a function that allows me to change the text and background colours in the DOS window. I copied it from someone else's program when I was looking through some programs on the internet. Please understand I don't know how this works, at least not now, but maybe eventually I will. But it works, so there.

I modified it a bit to give me a list of colours with their numbers. I use it for reference to know which number is which colour. Here it is. Oh and I do everything in Code Blocks (It's a free IDE compiler) www.codeblocks.org. Started with Dev C++ but it crashed a lot, Code Blocks hasn't given me any hassles yet. I save the files with the .cpp extension. Now here is the code for "textcol.cpp":


//Please note the first line of output will be blank because both the text and background is 
//BLACK so it looks like a blank line.

#include <windows.h>
#include <stdio.h>

void SetColorAndBackground(int ForgC, int BackC);
int main()
{
    int x,y;
    y=176;
    for(x=0;x<16;)
    {
    SetColorAndBackground(x,0);
    printf("%3i. Colour %c\n",x,y);
    x++;
    }
}
void SetColorAndBackground(int ForgC, int BackC)
{
     WORD wColor=((BackC & 0x0F)<< 4)+(ForgC & 0x0F);;
     SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), wColor);
     return;
}

_______________________________________________________________________
If we include the following in our code:

#include <windows.h>
void SetColorAndBackground(int ForgC, int BackC);

void SetColorAndBackground(int ForgC, int BackC)
{
     WORD wColor=((BackC & 0x0F)<< 4)+(ForgC & 0x0F);;
     SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), wColor);
     return;
}


we can say:


SetColorAndBackground(x,y);

Where x is the text colour and y is the background colour (get the numbers from "Textcol.cpp"). Any text printed after that line will have the colour attributes you set in x & y.

The original code can be found here:
http://codeincodeblock.blogspot.in/2011/03/text-background-color-of-console.html


No comments:

Post a Comment