Search code examples
c++windows-7colorsconsolewindow

Setting stdout/stderr text color in Windows


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 the below code.

This results in both stdout and stderr both getting colored red instead of stdout being green and stderr being red.

How do I solve this? My prompt is also now red but I don't care about that since I know how to fix it.

Should work in Windows 7. At the moment I'm building this from the prompt (using VS 2010 cl) and running it in a regular cmd prompt

#include <windows.h>
#include <stdio.h>
int main(int argc, char **argv)
{
    int i;
    unsigned long totalTime=0;


    HANDLE hConsoleOut; //handle to the console
    hConsoleOut = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleTextAttribute(hConsoleOut, FOREGROUND_GREEN);

    HANDLE hConsoleErr;
    hConsoleErr = GetStdHandle(STD_ERROR_HANDLE);
    SetConsoleTextAttribute(hConsoleErr, FOREGROUND_RED);

    fprintf(stdout, "%s\n", "out");
    fprintf(stderr, "%s\n", "err");
    return 0;
}

Solution

  • 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;