Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Colors in C++ win32 console

Tags:

c++

std::cout << "blblabla... [done]" << std::endl;

Is it possible to make [done] be in another color, and possibly bold? I'm using Windows 7

like image 798
tony Avatar asked Feb 27 '10 16:02

tony


People also ask

How do I change the background color of my console in C++?

In C++ programming, the default background of the output screen is black and the text color is the white color, the task is to color both the background and text color in the output screen. console_color = GetStdHandle(STD_OUTPUT_HANDLE); // P is color code according to your need.

How do you color only one line in C++?

C++ On windows you can use SetConsoleTextAttribute from the windows header.

What is set console text attribute?

Sets the attributes of characters written to the console screen buffer by the WriteFile or WriteConsole function, or echoed by the ReadFile or ReadConsole function. This function affects text written after the function call.


2 Answers

This depends on which OS you are using.

If you're using windows you want SetConsoleTextAttribute:

HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);  // Get handle to standard output
SetConsoleTextAttribute(hConsole, FOREGROUND_BLUE);

You can also combine values.

An application can combine the foreground and background constants to achieve different colors. For example, the following combination results in bright cyan text on a blue background.

FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY | BACKGROUND_BLUE

You can then use WriteFile or WriteConsole to actually write the the console.

like image 71
Brian R. Bondy Avatar answered Oct 03 '22 06:10

Brian R. Bondy


Yes, you just send a standard escape sequence, e.g.

    const char* green = "\033[0;32m";
    const char* white = "\033[0;37m";
    const char* red   = "\033[0;31m";
    double profit = round(someComplicatedThing());
    std::cout << (profit < 0 ? red : (profit > 0 ? green : white))
              << "Profit is " << profit << white << std::endl;

You also get bold vs normal, colored background etc. The Wikipedia page on ANSI escape code has details, the Bash-Prompt HOWTO has examples.

like image 29
Dirk Eddelbuettel Avatar answered Oct 03 '22 07:10

Dirk Eddelbuettel