I want to print to the console a message with multiple colors.
For example:
(red) error: (white) command not found
Is this possible?
I want to print to the console a message with multiple colors.
For example:
(red) error: (white) command not found
Is this possible?
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;
Console.ForegroundColor = ConsoleColor.Green;
Console.Write("Hello,");
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(" World!");
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: