Freigeben über


Console output with a transparent background color

In Windows land, if you want to print out colored text to a console, you will probably end up calling SetConsoleTextAttribute to set the desired color, then calling it again to restore the original settings. Unfortunately the documentation doesn't make it very clear how to change just the foreground color; which, in my experience, is a fairly common scenario. (You will still need to worry about clashing or unreadable text, but that is outside of the scope of this post.)

HANDLE consoleOut = GetStdHandle(STD_OUTPUT_HANDLE);

CONSOLE_SCREEN_BUFFER_INFO csbiInfo = {0};
GetConsoleScreenBufferInfo(consoleOut, &csbiInfo);

SetConsoleTextAttribute(consoleOut, FOREGROUND_INTENSITY | FOREGROUND_RED |
    (csbiInfo.wAttributes & (0x00F0)));

printf("Foreground red, background unchanged\n");

// restore the original colors
SetConsoleTextAttribute(consoleOut, csbiInfo.wAttributes);

The magic part is where we OR in the original attributes with a bit mask of 0x00F0 which just keeps the BACKGROUND_* values intact. The un-obvious (and extremely useful) thing to note, is that the original background will be kept intact even if it can't be expressed in the provided 4 bits of information (i.e. the user has defined a custom color using a 24-bit RGB value).