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 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
#include
// 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");
}