Wizard
Wizard

Reputation: 11265

How to change text or background color in a Windows console application

Which C++ function changes text or background color (MS Visual studio)? For example cout<<"This text"; how to make "This text" red color.

Upvotes: 3

Views: 30410

Answers (3)

Kerrek SB
Kerrek SB

Reputation: 477040

Colour isn't a C++ thing, but a property of your terminal. If your terminal speaks ANSI (e.g. any Linux terminal, or DOS or Windows NT if you add DEVICE=C:\DOS\ansi.sys to your config.sys, or later Windows if you call the shell with cmd.exe /kansicon), then you can try the following gimmick:

#define ANSI_COLOR_RED     "\x1b[31m"
#define ANSI_COLOR_GREEN   "\x1b[32m"
#define ANSI_COLOR_YELLOW  "\x1b[33m"
#define ANSI_COLOR_BLUE    "\x1b[34m"
#define ANSI_COLOR_MAGENTA "\x1b[35m"
#define ANSI_COLOR_CYAN    "\x1b[36m"

#define ANSI_COLOR_BRIGHT  "\x1b[1m"
#define ANSI_COLOR_RESET   "\x1b[0m"


std::cout << ANSI_COLOR_RED "Hello World\n" ANSI_COLOR_RESET;

Wikipedia has a list of ANSI escape sequences.

Upvotes: 9

Nasreddine
Nasreddine

Reputation: 37808

You can change the colors for a console application using Win32 and here's an example on how to:

#include "stdafx.h"
#include <Windows.h>
#include <iostream>

using namespace std; 

int main(void) 
{ 
    HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE); 
    if (hStdout == INVALID_HANDLE_VALUE) 
    {
        cout << "Error while getting input handle" << endl;
        return EXIT_FAILURE;
    }
    //sets the color to intense red on blue background
    SetConsoleTextAttribute(hStdout, FOREGROUND_RED | BACKGROUND_BLUE | FOREGROUND_INTENSITY);

    cout << "This is intense red text on blue background" << endl;
    //reverting back to the normal color
    SetConsoleTextAttribute(hStdout, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);

    return EXIT_SUCCESS;
}

Look at the MSDN documentation for the SetConsoleTextAttribute function and Console Screen Buffers for more information.

A more complete example on console applications using Win32 is available here.

Upvotes: 14

Daniel Trebbien
Daniel Trebbien

Reputation: 39208

I believe that you are looking for the SetConsoleTextAttribute function. The first parameter, hConsoleOutput, would be the standard output handle obtained via GetStdHandle(STD_OUTPUT_HANDLE). The second parameter is a bitwise-OR (|) combination of the desired character attributes.

See also: KB319883 How to change foreground colors and background colors of text in a Console window by using Visual C#

Upvotes: 2

Related Questions