Console Apps: Colour Text


Introduction

Whilst developing application running on theconsole is probably not the most exciting place, it is a great place touse for test harnesses or utilities. Of course when you are outputtingtext to the console window it can get pretty hard to see what's goingon – what you need to be able to do is change the colour of the outputtext…

However, one of my main gripes with the .Netframework is the amount of functionality missing form various areas -don't even get me started about some of the problems with theSystem.Net area. This articles gives a quick intro into how to resolvethe problems with the Console class.

.Net Console applications appear to use thewin32 standard console, implemented in "Kernel32.dll". This means thatall of the console functions documented in the Platform SDK will work.(see MSDN http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/conchar_3vg3.asp?frame=true) for the SDK details.

ConsoleColour.cs

using System;
using System.Runtime.InteropServices;

namespace PFitzsimons.ConsoleColour
{
/// <summary>
/// Static class for console colour manipulation.
/// </summary>
public class ConsoleColour
{
// constants for console streams
const int STD_INPUT_HANDLE = -10;
const int STD_OUTPUT_HANDLE = -11;
const int STD_ERROR_HANDLE = -12;

[DllImportAttribute("Kernel32.dll")]
private static extern IntPtr GetStdHandle
(
int nStdHandle // input, output, or error device
);

[DllImportAttribute("Kernel32.dll")]
private static extern bool SetConsoleTextAttribute
(
IntPtr hConsoleOutput, // handle to screen buffer
int wAttributes // text and background colors
);

// colours that can be set
[Flags]
public enum ForeGroundColour
{
Black = 0×0000,
Blue = 0×0001,
Green = 0×0002,
Cyan = 0×0003,
Red = 0×0004,
Magenta = 0×0005,
Yellow = 0×0006,
Grey = 0×0007,
White = 0×0008
}

// class can not be created, so we can set colours without a variable
private ConsoleColour()
{
}

public static bool SetForeGroundColour()
{
// default to a white-grey
return SetForeGroundColour(ForeGroundColour.Grey);
}

public static bool SetForeGroundColour(ForeGroundColour foreGroundColour)
{
// default to a white-grey
return SetForeGroundColour(foreGroundColour, true);
}

public static bool SetForeGroundColour(ForeGroundColour foreGroundColour, bool brightColours)
{
// get the current console handle
IntPtr nConsole = GetStdHandle(STD_OUTPUT_HANDLE);
int colourMap;

// if we want bright colours OR it with white
if (brightColours)
colourMap = (int)foreGroundColour | (int)ForeGroundColour.White;
else
colourMap = (int)foreGroundColour;

return SetConsoleTextAttribute(nConsole, colourMap);
}
}
}

Now that we have a console colour class we canuse it anywhere in our apps to change the current colour. Note that wecan use any standard .Net console calls, everythink will work – just incolourConsole.cs

// we want color output
using PFitzsimons.ConsoleColour;

namespace MyApp
{
public class MyApp
{
ConsoleColour.SetForeGroundColour(ConsoleColour.ForeGroundColour.Green);

Console.WriteLine("Text in green");

ConsoleColour.SetForeGroundColour(ConsoleColour.ForeGroundColour.Red);

Console.WriteLine("Text in red");

// reset console back to a default
ConsoleColour.SetForeGroundColour();
}
}

As you can see the code is pretty simple, but from a user point of view – its much easier to read the output.

Conclusion

As you can see, it's pretty straight forward,in production code you would expect have the class tell you what thecurrent console colour was, use properties rather than function etc -but I've tried to keep the code to a minimum to show how simple thisis.

If you read the SDK you will see that youcan also position the cursor, peek at console input (useful to see ifthe user has pressed a key), set font sizes and set the window title.These are all things that should have been in the Console class tobegin with – lets hope MS resolve this in the next version of theframework, until then we are all going to have to write ancillaryclasses to fix these kinds of ommisions.

<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0" width="468" height="60"><param name="movie" value="/banners/Ad2.swf?clickTAG=http://www.red-gate.com/products/ants_profiler/index.htm?utm_source=chelp%26utm_medium=banner%26utm_content=vsmenu%26utm_campaign=antsprofiler" /><param name="quality" value="high" /> <embed src="http://www.csharphelp.com/banners/Ad2.swf?clickTAG=http://www.red-gate.com/products/ants_profiler/index.htm?utm_source=chelp%26utm_medium=banner%26utm_content=vsmenu%26utm_campaign=antsprofiler" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="468" height="60"></embed> </object>

Twitter Digg Delicious Stumbleupon Technorati Facebook Email

No comments yet... Be the first to leave a reply!