Tuesday, December 22, 2009

Colored Output in C++ Console

Greetings!

I know I'm a day late, but there was a family emergency yesterday.

Our next topic is colored output in C++.
Have you ever wanted to get away from the boring white text on black background in console output? Well, I have an easy solution for you ;)

There is a wonderful function called SetConsoleTextAttribute. This function can set the output handle and the colors of the output (background and foreground).

It is a very easy function to use. Here is an example of the function:

SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 
BACKGROUND_INTENSITY | BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE);

First, the function keeps the output to the standard output (cout), then come the colors. There are three options for color in both foreground and background.

BACKGROUND_RED

BACKGROUND_GREEN

BACKGROUND_BLUE

FOREGROUND_RED

FOREGROUND_GREEN

FOREGROUND_BLUE


Use these as flags in the second part of the function's parameters, seperated by vertical lines (Shift+\).

If you are changing the background or foreground colors, you must also put:

FOREGROUND_INTENSITY
or
BACKGROUND_INTENSITY

depending on which color you are changing. The example function above changes the output to a white background (using all colors), with the "default" foreground (black). The color defaults to black when you do not choose it, if you use this function.

I used this function plenty to make a simulation program that included quizzes. I changed the colors of the incorrect or correct answers to visually stimulate the user.

One more thing: You need to include the windows.h header for this code to work. Use the following line in your code:


#include "windows.h"

I will upload test code when I can and link it to this post.


Until then,
Happy Coding!
kieblera5

No comments:

Post a Comment