Jim Lawless' Blog


Setting Text Color in a Batch File

Originally published on: Sat, 20 Mar 2010 23:37:57 +0000

Please note! If you're having difficulties compiling the C source code presented below, please see my post: Compiling C from the Command Line with Pelles C

Changing the text color in a Windows batch file can be done using the built-in color command. This command changes the color for the entire screen.

I wrote a utility called chgcolor that will set the current output color scheme so that only the output text that is written to the console window after using the utility is seen in the new color. When coupled with my echoj utility ( see Yet Another Enhanced Echo Command ), one can devise batch files that color individual sections of text.

The chgcolor utility accepts a single parameter that represents both the background color and the foreground color. Each is specified as a single hexadecimal digit from the table below:

If you invoke the command...

chgcolor 46

...you should then see all output as yellow text on a red background. The background color is specified as the first digit. If that digit is omitted, the background color will be set to black.

chgcolor 7

The above command sets the output color to white on black.

When you couple chgcolor with echoj, you can color specific words in your output text in a batch file. The echo command itself always writes a complete line of text, so echoj is used to output small fragments of text after changing the colors.

trycolor.bat


@echo off
chgcolor 07
echoj "How are "
chgcolor 4f
echoj "you"
chgcolor 07
echoj " today?"

If you run the above batch file, you'll see a single line of output that asks "How are you today?. The word "you" is emphasized in bright white text on a red background.

The C source code for chgcolor is as follows:

chgcolor.c


// Change the output color for the Windows console
//
// License: MIT / X11
// Copyright (c) 2009 by James K. Lawless
// jimbo@radiks.net http://www.radiks.net/~jimbo
// http://www.mailsend-online.com
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.

#include <windows.h>
#include <stdio.h>
#include <string.h>

void *getConsoleFunction(char *name);

BOOL (WINAPI *doSetConsoleTextAttribute)(HANDLE hConsoleOutput, WORD attr);


int main(int argc,char **argv) {
   HANDLE hCon;
   WORD color;
   
   if(argc<2) {
      fprintf(stderr,"chgcolor - Change console text color - by Jim Lawless\n\n");
      fprintf(stderr,"Syntax:\n\tchgcolor attribute\n\n");
      fprintf(stderr,"See:\nhttp://www.mailsend-online.com/blog?p=77\nfor usage instructions and C source code.\n");
      return 1;
   }
   sscanf(argv[1],"%x",&amp;color);
   
   hCon=GetStdHandle(STD_OUTPUT_HANDLE);
   
   doSetConsoleTextAttribute=getConsoleFunction("SetConsoleTextAttribute");

   if(doSetConsoleTextAttribute==NULL) {
      fprintf(stderr,"Sorry! chgcolor is incompatible with this version of Windows.");
      return 1;
   }
   (*doSetConsoleTextAttribute)(hCon,color);

   return 0;
}

void *getConsoleFunction(char *name) {
   static HMODULE kernel32=(HMODULE)0xffffffff;
   if(kernel32==0)
      return NULL;
   if(kernel32==(HMODULE)0xffffffff) {
      kernel32=LoadLibrary("kernel32.dll");
      if(kernel32==0)
         return 0;
   }
   return GetProcAddress(kernel32,name);
}

If you decide to tinker with the source code, you may also wish to read my post Setting Windows Console Text Colors in C.

The source code and executable file for colordemo can be downloaded from a single archive at: http://www.mailsend-online.com/wp/chgcolor.zip

Unless otherwise noted, all code and text entries are Copyright 2010 by James K. Lawless



Views expressed in this blog are those of the author and do not necessary reflect those of the author's employer. Views expressed in the comments are those of the responding individual.

stumbleupon Save to StumbleUpon
digg Digg it
reddit Save to Reddit
facebook Share on Facebook
twitter Share on Twitter
aolfav More bookmarks


Previous post: Pi Day Meets the HTML5 Canvas
Next post:Setting Windows Console Text Colors in C


About Jim ...


Follow me on Twitter

http://twitter.com/lawlessGuy


My GitHub Repository

https://github.com/jimlawless


Recent Posts

Compiling C from the Command Line with Pelles C

A Forthcoming Marvel Movie Villain

Uninstalling Problematic Windows Software

Don't be Hatin'

A JavaScript REPL for Android Devices

MailSend is Free

My Blog Engine

The October 10th Bug


Random Posts

JRuby as a Java Obfuscation Utility

An Interview with Tom Zimmer: Forth System Developer

Expanding Shortened URL's

Getting the Windows Console Text Color

An Interview with Brad Templeton

My Foray into Shareware

Auto Save Images from the Clipboard

WSH JavaScript Includes

Compiling Rhino JavaScript to Java

A Review of Kevin Mitnick's Book Ghost in the Wires


Full List of Posts

http://www.mailsend-online.com/bloglist.htm


Recent Posts from my Other Blog

Yet Another Seven Languages in Seven Weeks

Happy 50th Birthday, BASIC

Extending Commodore 64 BASIC

Hide the HTTP-Referer using HTML and JS

RSS Feed Processing in Python

A Chromecast Slideshow using Python

A Simple Perl REPL

Linux Mint on a Toshiba Netbook

Find and View All Images on a HD with Perl

Pretty-Printing an s-expression in Go

My Personal Text to HTML Utility

1985 Computing : Atari and Commodore

My Mac has Mono

Yet Another Config File Reader for Go (Golang)

Filling a Slice Using Command-line Flags in Go (Golang)

An RPN Interpreter in Go (Golang)

Simulating Try-Catch in Go (Golang)

Sending GMail with Go (Golang)

Variant Types in Golang

My First C64 Interrupt Program

The Triangles Puzzle

Happy 25th, Perl !

My Favorite BASIC One-Liner

Playing with OS/X Text to Speech

The Villain at the end of Marvel's Avengers Move is...

Chicken! Fight like a Robot!

Processing GMail items with Ruby

The Squares Puzzle

Happy 30th Birthday, Commodore 64

Scripting Safari

MailWrench CSharp Command Line Mailer for Windows is now Free Software

Welcome Back, M.U.L.E. !

Rainy Day Fun with the HTML DOM

Building a World War II Foxhole Radio

Prototerp Unleashing a JavaScript REPL via the Mobile Browser

Steal This Bookmarklet

Happy Birthday, Miles