Colorizing text in the console with C++

后端 未结 12 2555
礼貌的吻别
礼貌的吻别 2020-11-27 10:04

How can I write colored text to the console with C++? That is, how can I write different text with different colors?

12条回答
  •  执念已碎
    2020-11-27 10:42

    In Windows, you can use any combination of red green and blue on the foreground (text) and the background.

    /* you can use these constants
    FOREGROUND_BLUE
    FOREGROUND_GREEN
    FOREGROUND_RED
    FOREGROUND_INTENSITY
    BACKGROUND_BLUE
    BACKGROUND_GREEN
    BACKGROUND_RED
    BACKGROUND_INTENSITY
    */
    
    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleTextAttribute(hConsole, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY);
    std::cout << "I'm cyan! Who are you?" << std::endl;
    

    Source: https://msdn.microsoft.com/en-us/library/windows/desktop/ms682088(v=vs.85).aspx#_win32_character_attributes

提交回复
热议问题