Skip to main content

Adding color to console output (text + background) (🟢 Beginner)

Here is a new example illustrating a practical trick with xtd: how to add color to console output.

With xtd, you can do the same in a clean, portable and type-safe way — without worrying about platform-specific APIs or ANSI escape codes.

Modern C++ code with ANSI​

#include <print>

auto main() -> int {
constexpr auto back_color_dark_blue = "\x1b[44m";
constexpr auto fore_color_red = "\x1b[91m";
constexpr auto fore_color_white = "\x1b[97m";
constexpr auto reset_color = "\x1b[0m";

std::print(fore_color_red);
std::println("I'm a red text color");
std::print(back_color_dark_blue);
std::print(fore_color_white);
std::println("I'm a white text on dark blue background color");
std::print(reset_color);
}

Modern C++ code with Win32 API​

#define UNICODE
#include <Windows.h>

auto main() -> int {
auto csbi = CONSOLE_SCREEN_BUFFER_INFO {};
auto original_attributes = GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi) == TRUE ? csbi.wAttributes : 0x00;
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_INTENSITY);
WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), L"I'm a red text color\n", 21, nullptr, nullptr);
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), BACKGROUND_BLUE | FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);
WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), L"I'm a white text on dark blue background\n", 41, nullptr, nullptr);
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), original_attributes);
}

xtd code​

#include <xtd/xtd>

auto main() -> int {
console::foreground_color(console_color::red);
console::write_line("I'm a red text");
console::foreground_color(console_color::white);
console::background_color(console_color::dark_blue);
console::write_line("I'm a white text on dark blue background");
}

or simply

#include <xtd/xtd>

auto main() -> int {
// You can also use console::out as a stream like std::cout
console::out << foreground_color(console_color::red) << "I'm a red text" << environment::new_line;
console::out << foreground_color(console_color::white) << background_color(console_color::dark_blue) << "I'm a white text on dark blue background" << environment::new_line;

Use​

If we launch the application:

./my_app

The result will be:

console_color

Remarks​

See also​