![Input / Output](icons/IO.png)
.NET 2.0+Console Applications and Colour
Console applications are useful for simple applications and tools, particularly where complex user interfaces are not required. However, plain white on black text can be difficult to read quickly. Using colour in console applications can improve output.
Console Class
The Console class is a static class that is used to control textual input and output for console applications. A console application runs within a simple text window, identical to that displayed when the Command Prompt utility is executed.
Console Colour Properties
The output from a console application is coloured according to the user's preferences for the command prompt utility. If the preferences have not been modified, the console application will use grey text on a black background.
To highlight elements of text in a console application, two static properties of the Console class can be changed. These are the ForegroundColor and BackgroundColor properties. Each property accepts a value from the ConsoleColor enumeration, which contains sixteen colour constants. Once set, the colours are used for all new text outputted to the console.
The following code shows the sixteen available colours by looping through the enumeration. Each colour is outputted on a black background except for black, which is contrasted against white.
foreach (ConsoleColor c in Enum.GetValues(typeof(ConsoleColor)))
{
Console.ForegroundColor = c;
if (c != ConsoleColor.Black)
Console.BackgroundColor = ConsoleColor.Black;
else
Console.BackgroundColor = ConsoleColor.White;
Console.WriteLine("{0}", c);
}
Resetting the Colours
Sometimes you will want to return to the default colours for the console. Rather than storing the original colours in variables so that they can be reset, you can use the Console class's static method, ResetColor. This resets both the foreground and background colours
10 April 2008