How to change the colours in a .NET console application

Sometimes you need to change the fore- and background colours in your .NET console application. Normally it’s fine with the traditional black background and white foreground colours – or whatever the user has set as default colours – however, some message types may deserve extra attention.

This short post will demonstrate how to change the colours in a console application.

Exception messages can be highlighted in red font. Most often the console window background is black and reading red text on a black background can be difficult. Therefore I think it might be better to change the background to red instead:

private static void ChangeColours()
{
	Console.WriteLine("Before throwing the exception...");
	try
	{
		throw new ArgumentNullException("You've entered an invalid value.");
	}
	catch (Exception ex)
	{
		HandleException(ex);
	}
	Console.WriteLine("After handling the exception...");
}

private static void HandleException(Exception ex)
{
	ConsoleColor originalBgColour = Console.BackgroundColor;
	ConsoleColor originalFgColour = Console.ForegroundColor;
	Console.ForegroundColor = ConsoleColor.White;
	Console.BackgroundColor = ConsoleColor.Red;
	Console.WriteLine("An exception has occurred: {0}", ex.Message);
	Console.BackgroundColor = originalBgColour;
	Console.ForegroundColor = originalFgColour;
}

If you run ChangeColours you’ll get an output similar to the following:

Example of red background

The ConsoleColor enumeration includes the possible console colour types.

You can follow a similar strategy for warning messages. Warnings are normally printed in yellow.

Another case where various colours are used is console apps where the colours are used to denote messages that belong together. E.g. if a program starts various threads and you’d like to show how different threads are linked then you can dedicate some colour to each and see their output. This can work as a rudimentary debugging tool as well.

View all various C# language feature related posts here.

Advertisement

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: