0

I am working on creating a class to support a console app I am developing, and I would like to create a method within to change both the background and foreground color. Is there a way to set a ConsoleColor value (which I believe is an enum) to another variable so this can easily be changed by the user at runtime? For instance, I am hoping for something like the following.

Public class ConsoleOutput
{
  private var consoleBackground = ConsoleColor.White;
  private var consoleForeground = ConsoleColor.Black;
  
  Public ConsoleOutput
  {
    Console.BackgroundColor = consoleBackground
    Console.ForegroundColor = consoleForeground
  }
}

This, however, did not work.

1 Answer 1

1

You don't seem to ever write to the console in your program, which you obviously need to do. Other then that you also need a way to change the colors during runtime using e.g. setters or a function like ChangeColors().

Here a working sample program for reference:

namespace MyProgram;

class Program
{
    static void Main(string[] args)
    {
        var coloredPrinter = new ColoredPrinter(ConsoleColor.White, ConsoleColor.Blue);
        coloredPrinter.WriteLine("This is white text on blue background");
        coloredPrinter.ChangeColors(ConsoleColor.Yellow, ConsoleColor.Red);
        coloredPrinter.WriteLine("This is yellow text on red background");
        Console.WriteLine("This is the default");
    }
}

class ColoredPrinter
{
    public ConsoleColor ForegroundColor { get; set; }
    public ConsoleColor BackgroundColor { get; set; }

    public ColoredPrinter(ConsoleColor foregroundColor, ConsoleColor backgroundColor)
    {
        ChangeColors(foregroundColor, backgroundColor);
    }

    public void ChangeColors(ConsoleColor foregroundColor, ConsoleColor backgroundColor)
    {
        ForegroundColor = foregroundColor;
        BackgroundColor = backgroundColor;
    }

    public void WriteLine(string text)
    {
        Console.ResetColor();
        Console.BackgroundColor = BackgroundColor;
        Console.ForegroundColor = ForegroundColor;
        Console.WriteLine(text);
        Console.ResetColor();
    }
}

This prints out the following:

colored console output

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.