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.

  1. ConsoleColor background = Console.BackgroundColor;
  2. ConsoleColor foreground = Console.ForegroundColor;

The following code snippet sets the foreground and the background colors of the console.

  1. Console.ForegroundColor = ConsoleColor.White;
  2. Console.BackgroundColor = ConsoleColor.Red;

After ForegroundColor and BackgroundColor values are set, call Console.Clear() to apply it to the entire background and foreground.

  1. Console.Clear();
The ResetColor method resets the console’s default foreground and background colors.
  1. Console.ResetColor();

Listing 1 is the complete code that loops through all Console colors and changes console’s background and foreground colors.

  1. using System;
  2. class ConsoleColorsClass {
  3. static void Main(string[] args) {
  4. // Let's go through all Console colors and set them as foreground
  5. foreach(ConsoleColor color in Enum.GetValues(typeof(ConsoleColor))) {
  6. Console.ForegroundColor = color;
    Console.Clear();
  7. Console.WriteLine($ "Foreground color set to {color}");
  8. }
  9. Console.WriteLine("=====================================");
  10. Console.ForegroundColor = ConsoleColor.White;
  11. // Let's go through all Console colors and set them as background
  12. foreach(ConsoleColor color in Enum.GetValues(typeof(ConsoleColor))) {
  13. Console.BackgroundColor = color;
  14. Console.WriteLine($ "Background color set to {color}");
  15. }
  16. Console.WriteLine("=====================================");
  17. // Restore original colors
  18. Console.ResetColor();
  19. Console.ReadKey();
  20. }
  21. }
Listing 1.

The output of Listing 1 generates Figure 1.


Figure 1