Setting stdout/stderr text color in Windows

后端 未结 3 1709
猫巷女王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;
    
    0 讨论(0)
  • 2020-12-11 05:07

    The handle for error and normal console output are the same. Or more like, they point to the same console window. When you change the console color, it applies to all text written after that, so you'd need to change the color directly before the output. If you don't want to do that for every text you output, pack the calls into a seperate function:

    #include <windows.h>
    #include <stdio.h>
    // global vars (better pack it in a class)
    // initialize both to normal white color
    #define FOREGROUND_WHITE (FOREGORUND_RED | FOREGROUND_BLUE | FOREGROUND_GREEN)
    int g_console_out_color = FOREGROUND_WHITE;
    int g_console_err_color = FOREGROUND_WHITE;
    HANDLE g_console_out_handle = GetStdHandle(STD_OUTPUT_HANDLE);
    HANDLE g_console_err_handle = GetStdHandle(STD_ERROR_HANDLE);
    
    void SetConsoleOutColor(int color){
        g_console_out_color = color;
    }
    
    void SetConsoleErrColor(int color){
        g_console_err_color = color;
    }
    
    void PrintOut(const char* format, ...){
        SetConsoleTextAttribute(g_console_out_handle, g_console_out_color);
        va_list args;
        va_start(args, str);
        fprintf(stdout, format, args);
        va_end(args);
        // set color back to normal
        SetConsoleTextAttribute(g_console_out_handle, FOREGROUND_WHITE);
    }
    
    void PrintErr(const char* format, ...){
        SetConsoleTextAttribute(g_console_err_handle, g_console_err_color);
        va_list args;
        va_start(args, str);
        fprintf(stderr, format, args);
        va_end(args);
        // set color back to normal
        SetConsoleTextAttribute(g_console_err_handle, FOREGROUND_WHITE);
    }
    
    int main(void){
        PrintOut("%s\n", "out");
        PrintErr("%s\n", "err");
    }
    
    0 讨论(0)
  • 2020-12-11 05:26

    Try to set the color before each output. You can do that in a function to avoid code duplication.

    0 讨论(0)
提交回复
热议问题