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

前端 未结 3 917
后悔当初
后悔当初 2020-12-02 02:37

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

3条回答
  •  伪装坚强ぢ
    2020-12-02 03:08

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

    #include "stdafx.h"
    #include 
    #include 
    
    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.

提交回复
热议问题