0

I want to print to the console a message with multiple colors.

For example: (red) error: (white) command not found

Is this possible?

Tal
  • 43
  • 1
  • 7

3 Answers3

0

You can try Console.Write() to continue on the same line with different colors.

Code goes like this -

var originalColor = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Red;
Console.Write("error: ");
Console.ForegroundColor = ConsoleColor.White;
Console.Write("command not found");
Console.ForegroundColor = originalColor;

Output - enter image description here

  • Would using [this](https://github.com/silkfire/Pastel) be more or less efficient? I found it a while after asking the question. – Tal Oct 22 '21 at 15:08
  • It will be efficient if you are considering your code writing efforts. Also, if your application is very small and not a large scale application, using a packaged library will only increase the load on your project. There is always a trade-off when we are talking about efficiency. A wise decision depends on what your application requirements are or how are they going to be extended in future. – dark_cypher Oct 22 '21 at 19:01
0
Console.ForegroundColor = ConsoleColor.Green;
Console.Write("Hello,");
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(" World!");

enter image description here

Petter Hesselberg
  • 5,062
  • 2
  • 24
  • 42
0

You can set Console.ForegroundColor property.
First, create a class representing a fragment of your string See the example below:

public string StringFragment { get; set; }

public ConsoleColor StringFragmentColor { get; set; }

public SpecialString(string wordFragment, ConsoleColor color)
{
    this.StringFragment = wordFragment;
    this.StringFragmentColor = color;
}

public void Display()
{
    Console.ForegroundColor = this.StringFragmentColor;
    Console.Write(this.StringFragment);
}

And then, just call them in your code...

var wordFragment1 = new SpecialString("Hello", ConsoleColor.Green);
var wordFragment2 = new SpecialString(" World", ConsoleColor.Yellow);

wordFragment1.Display();
wordFragment2.Display();

Result:
enter image description here

Peter Csala
  • 17,736
  • 16
  • 35
  • 75