In one of my recent applications, I needed to change the foreground and the background colors of the system console.
The Console class in C# represents the system console. We can achieve this by setting Console’s foreground and background properties. The ConsoleColor enum represents a value of the console color. Keep in mind, the ConsoleColor supports a limited number of colors only.
The following code snippet returns the current background and the foreground colors of the console.
- ConsoleColor background = Console.BackgroundColor;
- ConsoleColor foreground = Console.ForegroundColor;
The following code snippet sets the foreground and the background colors of the console.
- Console.ForegroundColor = ConsoleColor.White;
- Console.BackgroundColor = ConsoleColor.Red;
After ForegroundColor and BackgroundColor values are set, call Console.Clear() to apply it to the entire background and foreground.
The ResetColor method resets the console’s default foreground and background colors.
Listing 1 is the complete code that loops through all Console colors and changes console’s background and foreground colors.
- using System;
- class ConsoleColorsClass {
- static void Main(string[] args) {
-
- foreach(ConsoleColor color in Enum.GetValues(typeof(ConsoleColor))) {
- Console.ForegroundColor = color;
Console.Clear();
- Console.WriteLine($ "Foreground color set to {color}");
- }
- Console.WriteLine("=====================================");
- Console.ForegroundColor = ConsoleColor.White;
-
- foreach(ConsoleColor color in Enum.GetValues(typeof(ConsoleColor))) {
- Console.BackgroundColor = color;
- Console.WriteLine($ "Background color set to {color}");
- }
- Console.WriteLine("=====================================");
-
- Console.ResetColor();
- Console.ReadKey();
- }
- }
Listing 1.
The output of Listing 1 generates Figure 1.
Figure 1