Setting stdout/stderr text color in Windows

后端 未结 3 1711
猫巷女王i
猫巷女王i 2020-12-11 05:03

I tried using system(\"color 24\"); but that didn\'t change the color in the prompt. So after more Googling I saw SetConsoleTextAttribute and wrote

3条回答
  •  一向
    一向 (楼主)
    2020-12-11 05:05

    According to the MSDN GetStdHandle() documentation, the function will return handles to the same active console screen buffer. So setting attributes using these handles will always change the same buffer. Because of this you have to specify the color right before you right to the output device:

    /* ... */
    
    HANDLE hConsoleOut; //handle to the console
    HANDLE hConsoleErr;
    hConsoleErr = GetStdHandle(STD_ERROR_HANDLE);
    hConsoleOut = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleTextAttribute(hConsoleOut, FOREGROUND_GREEN);
    fprintf(stdout, "%s\n", "out");
    
    SetConsoleTextAttribute(hConsoleErr, FOREGROUND_RED);
    fprintf(stderr, "%s\n", "err");
    return 0;
    

提交回复
热议问题