Color console output with C++ in Windows

前端 未结 4 1160
面向向阳花
面向向阳花 2020-12-14 11:52

Is there a way to output colored text to the console? I am using Visual Studio 2010, and only need the code to work in Windows.

I have been unsuccessful in finding a

4条回答
  •  旧巷少年郎
    2020-12-14 12:23

    I took this code from here:

    // color your text in Windows console mode
    // colors are 0=black 1=blue 2=green and so on to 15=white
    // colorattribute = foreground + background * 16
    // to get red text on yellow use 4 + 14*16 = 228
    // light red on yellow would be 12 + 14*16 = 236
    // a Dev-C++ tested console application by vegaseat 07nov2004
    
    #include 
    #include  // WinApi header
    
    using namespace std; // std::cout, std::cin
    
    int main()
    {
    HANDLE hConsole;
    int k;
    
    hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    
    // you can loop k higher to see more color choices
    for(k = 1; k < 255; k++)
    {
    // pick the colorattribute k you want
    SetConsoleTextAttribute(hConsole, k);
    cout << k << " I want to be nice today!" << endl;
    }
    
    cin.get(); // wait
    return 0;
    }
    

提交回复
热议问题