/*++ >>> This code is released to the public domain. No warranty whatsoever is provided, use it at your own risk. <<< Module Name: myecho.c Abstract: An "echo" replacement that can do color text. Invoke like this: myecho.exe [-fg color] [-bg color] "string to echo" color can be: blue, red, green, yellow, cyan, violet, pink, black, white brightblue, brightred, brightgreen, brightyellow, brightviolet, brightpink, brightblack, gray, grey, or brightwhite Author: Scott Gasch (scott@gasch.org) 22 Aug 2002 Revision History: --*/ #include #include #include WORD MakeColor(BOOL fBg, char *sz) /*++ Routine description: Based on a string, return a color WORD. Parameters: BOOL fBg, char *sz Return value: WORD --*/ { WORD w = 0; // // bright // if (strstr(sz, "bright")) { w = FOREGROUND_INTENSITY; } // // colors // if (strstr(sz, "blue")) { w |= FOREGROUND_BLUE; } if (strstr(sz, "red")) { w |= FOREGROUND_RED; } if (strstr(sz, "green")) { w |= FOREGROUND_GREEN; } if (strstr(sz, "yellow")) { w |= (FOREGROUND_RED | FOREGROUND_GREEN); } if (strstr(sz, "cyan")) { w |= (FOREGROUND_BLUE | FOREGROUND_GREEN); } if ((strstr(sz, "violet")) || (strstr(sz, "pink"))) { w |= (FOREGROUND_BLUE | FOREGROUND_RED); } if (strstr(sz, "white")) { w |= (FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); } if (strstr(sz, "black")) { w &= ~(FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); } if (strstr(sz, "gray") || strstr(sz, "grey")) { w &= ~(FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); w |= FOREGROUND_INTENSITY; } if (fBg) { w <<= 4; } return(w); } int __cdecl main(int argc, char *argv[]) /*++ Routine description: Program entry point; see above for usage. Parameters: int argc, char *argv[] Return value: int --*/ { CONSOLE_SCREEN_BUFFER_INFO csbiInfo; HANDLE hStdOut; WORD wAttr; int x; BOOL fNewline = TRUE; // // open stdout // hStdOut = GetStdHandle(STD_OUTPUT_HANDLE); if (INVALID_HANDLE_VALUE == hStdOut) { fprintf(stderr, "Failed to open handle to stdout, error=%u.\n", GetLastError()); exit(1); } // // Save the current text colors. // if (0 == GetConsoleScreenBufferInfo(hStdOut, &csbiInfo)) { fprintf(stderr, "Failed to save current text attr, error=%u\n", GetLastError()); exit(1); } // // echo the string(s) // x = 1; while (x < argc) { if (!_strcmpi(argv[x], "-fg")) { x++; if (x < argc) { SetConsoleTextAttribute(hStdOut, MakeColor(0, argv[x])); } x++; } else if (!_strcmpi(argv[x], "-bg")) { x++; if (x < argc) { SetConsoleTextAttribute(hStdOut, MakeColor(1, argv[x])); } x++; } else if (!_strcmpi(argv[x], "-n")) { fNewline = FALSE; x++; } else { printf(argv[x]); if (TRUE == fNewline) { printf("\n"); } x++; } } // // restore the old text colors // (void)SetConsoleTextAttribute(hStdOut, csbiInfo.wAttributes); }