/* Read http://z0b.kapsi.fi/snippets.php before using this code. Thank you. */ /* I might add support for background colors and Unicode later. */ #include #include static int originalAttributes = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE; static void getOriginalAttributes() { CONSOLE_SCREEN_BUFFER_INFO info; if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info)) originalAttributes = info.wAttributes; } static void cprintf(const char *fmt, ...) { static const unsigned int colors[] = { 0, FOREGROUND_BLUE, FOREGROUND_GREEN, FOREGROUND_GREEN | FOREGROUND_BLUE, FOREGROUND_RED, FOREGROUND_RED | FOREGROUND_BLUE, FOREGROUND_RED | FOREGROUND_GREEN, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE, FOREGROUND_INTENSITY, FOREGROUND_INTENSITY | FOREGROUND_BLUE, FOREGROUND_INTENSITY | FOREGROUND_GREEN, FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_BLUE, FOREGROUND_INTENSITY | FOREGROUND_RED, FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_BLUE, FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN, FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE, }; if (!fmt) return; HANDLE con = GetStdHandle(STD_OUTPUT_HANDLE); if (!con) return; // format static char buf[2048]; va_list ap; va_start(ap, fmt); vsnprintf(buf, 2046, fmt, ap); buf[2047] = '\0'; va_end(ap); // and print const char *c; char *p = buf; while (*p) { // find the next color change char *s = strchr(p, '#'); if (s) { // color changes, terminate current block and show it *s = '\0'; for (c = p; *c; ) putchar(*c++); // then change the color (or print a hash sign) if (*(s + 1)) { const char c = *++s; if (c >= '0' && c <= '9') SetConsoleTextAttribute(con, colors[c - '0']); else if (c >= 'A' && c <= 'F') SetConsoleTextAttribute(con, colors[c - 'A' + 10]); else if (c >= 'a' && c <= 'f') SetConsoleTextAttribute(con, colors[c - 'a' + 10]); else if (c == 'R') SetConsoleTextAttribute(con, originalAttributes); else if (c == '#') putchar('#'); } // jump over this block and the color change p = s + 1; } else { // no more color changes, print the // rest of the string and stop for (c = p; *c; ) putchar(*c++); break; } } } int main() { getOriginalAttributes(); cprintf("#CHe#Ell#Ao w#9or#Dld#F!#R\n"); return 0; }