Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
608 views
in Technique[技术] by (71.8m points)

c++ - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...