How to change the colours in a .NET console application
October 9, 2015 Leave a comment
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:
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.