Wednesday, July 27, 2011

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


Read more: Software Sleuthing
QR: console-output-with-a-transparent-background-color.aspx

Posted via email from Jasper-Net