Friday, January 4, 2013

Console Window - Colored Text


Colored Text

If you've ever wanted to use colors in a console window, as in having a colorful text and backgrounds, then are two primary methods:
  • the System ( ) method
  • the SetConsoleTextAttribute ( ) method


  • The System ( ) can be used on several operating systems but doesn't allow multiple colors to appear at once. SetConsoleTextAttribute ( ) requires the <Windows.h> library is included but will allow multiple colors at once.

    Both use color codes of a hexadecimal notation, such as FF. The first digit is the background and the second is the text or foreground. For a complete color table, see the final output example.

    The System ( ) Method

    System("color F0"); which changes the color of the environment. Consider the following:

    Using the system( ) function
    main.cpp
    //===================================INCLUDES==================================
    #include <iostream>

    Assuming namespace ::std.
    using namespace std;

    //==================================MAIN ENTRY=================================
    int main ( void )
    {
        //Set the system color to 0xC1.
        system("color C1");

        //Output some text to the screen.
        cout << "This text is made colorful by the system( ) function." << endl;

        return ( 0 );
    }


    Outputs:



    SetConsoleTextAttribute ( ) Method


    The SetConsoleTextAttribute ( ) method allows for much more control over coloring text.
    Using the system( ) function
    main.cpp
    //===================================INCLUDES==================================
    #include <iostream>
    #include <Windows.h>

    Assuming namespace ::std.
    using namespace std;

    //==================================MAIN ENTRY=================================
    int main ( void )
    {
        //Handle to console window's context.
        HANDLE hConsole = GetStdHandle ( STD_OUTPUT_HANDLE );


        //Set the color (0x0E = Black Background, Yellow Foreground )
        SetConsoleTextAttribute ( hConsole, 0x0E );

        cout << "Text made colorful by SetConsoleTextAttribute( ) function." << endl;

        return ( 0 );
    }



    In-Depth SetConsoleTextAttribute ( ) Method

    In this example we'll create a function, GetColorCode ( ) and loop through all the possible colors.
    The SetConsoleTextAttribute ( ) Method
    main.cpp
    //===================================INCLUDES==================================
    #include <iostream>
    #include <iomanip>
    #include <Windows.h>

    using namespace std;


    //=============================FUNCTION PROTOTYPES=============================
    unsigned char GetColorCode ( unsigned char colorBackground,
                                 unsigned char colorForeground );


    //==================================MAIN ENTRY=================================
    int main( void )
    {
          //handle to console window's context
          HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);

          unsigned char colorBackground = 0x00; //background color code
          unsigned char colorForeground = 0x00;//foreground color code
          unsigned char colorCode = 0x00; //high:background, low:foreground


          //---------------OUTPUT COLORFUL LITERAL---------------
          //set text color (0x08 = black background, grey foreground)
          SetConsoleTextAttribute ( hConsole, 0x08 );
          cout << "I don't always like ";

          //set text color (0x0E = black background, yellow foreground)
          SetConsoleTextAttribute(hConsole, 0x0E);
          cout << "Cake";

          //set text color (0x08 = black background, grey foreground)
          SetConsoleTextAttribute(hConsole, 0x08);
          cout << ", but when I do it's always a ";

          //set text color (0xC0 = red background, black foreground)
          SetConsoleTextAttribute(hConsole, 0xC0);
          cout << "Lie!" << endl << endl << endl;



          //------------------OUTPUT COLOR CHART-----------------
          //output hexidecimal notation
          cout << setbase(16);

          //loop through each background color (0 to 15 = 16 possible colors)
          for (colorBackground = 0; colorBackground < 16; colorBackground++)
          {

               //loop through each foreground color (0 to 15 = 16 possible colors)
               for (colorForeground = 0; colorForeground < 16; colorForeground++)
               {

                    //get color code as one variable
                    colorCode = GetColorCode(colorBackground, colorForeground);

                    //set front and back colors
                    SetConsoleTextAttribute(hConsole, colorCode);

                    //output the color code
                    cout << setfill('0')                 //set fill character
                         << setw(2)                      //create width for numbers
                         << uppercase                    //set output to uppercase
                         << static_cast<int>(colorCode)  //print colorCode as hex
                         << ' ';                         //padding for next value
               }

              //start new line for next background color
              cout << '\n';
          }

          return ( 0 );
    }


    //=============================FUNCTION DEFINITIONS============================
    unsigned char GetColorCode ( unsigned char colorBackground,
                                 unsigned char colorForeground )
    {
          //return most signifigant bit of colorBackground and
          //least signifigant bit of colorForground as one byte
          return (colorBackground << 4) + colorForeground;
    }

     Outputs:


    The program creates a HANDLE or a context of the console environment to affect the color code of that environment. Next we create an unsigned char for the colorBackground, the background of the text area, colorForeground, the foreground of the text itself, and colorCode, both the background and foreground combined into a single hexadecimal number.
    Since the colorCode is actually two hexidecimal digits, or places, which can never be negative we use unsigned. The reason we use char, despite the fact that the background color is only 4 bits, compared to the char being 8 bits, is because there is no smaller variable size availible (other than bool).

    We are only using four bits from each code, again, because the color code is only 8 bits, we must later take the four bits from ColorBackground (which are the left-most, or the high bits) and add in the colorForground bits.

    To make this intuitive:
    colorBackground = 1111 0000b;
    colorForeground = 0000 1111b;

    After we call GetColorCode(colorBackground, colorForeground) the colorCode would be equal to 1111 1111b.

    No comments:

    Post a Comment