Introduction
This article will give you some insight on using Ansi Colors within your projects. The main use that I have used this code for is when I build a Windows service. Usually I add in a tcplistener so that multiple users can telnet to the server and command it. Adding colors to the output makes viewing information easier on the eyes. This code would also be useful for anyone interested in creating a MUD.
This code does NOT work from the command prompt. If anyone is interested in an article dealing with that, please write a comment and let me know.
Background
This article will require you to have very little programming knowledge. Knowing how to use a collection and the TcpListener class will help you out.
Using the Code
The source code is very simple to use. I have created a helper class called AnsiColor. This class contains the static method AnsiColor.Colorize that will accept a string and parse out any colors that you have entered. Here is a very simple sample for using the code:
string colorString = AnsiColor.Colorize
( "{red}This is red!\r\n{blue}This is blue\r\n{!red}With a red background.\r\n" );
In the example project, I have added a small TcpListener so that you may test the demo by using the telnet program. Simply start the demo and telnet to localhost port 5484. I will not be explaining anything about TcpListener as there are many great references here on the interweb.
Because you can highlight both foreground and background, custom effects can be created. Here is a function that will create a simple progress bar:
public static string ProgressBarDemo
( int percent, int width, string colorCode )
{
int MaxSize = 10;
if ( percent < 0 || percent > 100 ) percent = 0;
int blocks = ( int ) ( ( percent / 100f ) * width );
string progressBar = "{" + colorCode;
for ( int i = 0; i < blocks; i++ )
progressBar += ' ';
progressBar += "{reset}";
for ( int i = 0; i < width - blocks; i++ )
progressBar += ' ';
progressBar += '}';
return ( "Progress Bar: " + Colorize ( progressBar ) + "\r\n" );
}
This function exists within the AnsiColor class, as well as a ColorDemo function that loops through all of the codes and displays the results.
Points of Interest
When using the .NET string formatting functions (string.Format), you have to beware of your curly brackets { & }s. For example, take this code:
string.Format ( "{red}{0}{reset}", "This is red text!" );
This will give you compiler errors because when formatting text, the curly brackets are special characters. The proper syntax would actually be:
string.Format ( "{{red}}{0}{{reset}}", "This is red text!" );
References
History