I need to colorize strings by method, so I use Console.ForegroundColor
property and write text later, but I have made a mistake on somewhere, so all line is one colored. Or is there a better solution? I need to colorize string by &0-&f (hex) and output it to console, here is my solution:
public static void ColorizeConsoleMessage(string message)
{
var matches = Regex.Matches(message, "&+[0-9a-f]");
var split = Regex.Split(message, "&+[0-9a-f]");
var def = Console.ForegroundColor;
var i = 0;
foreach (var match in matches)
{
switch (match.ToString().Replace("&", "").ToCharArray()[0])
{
case '0':
Console.ForegroundColor = ConsoleColor.White;
break;
case '1':
Console.ForegroundColor = ConsoleColor.Gray;
break;
case '2':
Console.ForegroundColor = ConsoleColor.DarkGray;
break;
case '3':
Console.ForegroundColor = ConsoleColor.Black;
break;
case '4':
Console.ForegroundColor = ConsoleColor.Red;
break;
case '5':
Console.ForegroundColor = ConsoleColor.Green;
break;
case '6':
Console.ForegroundColor = ConsoleColor.Blue;
break;
case '7':
Console.ForegroundColor = ConsoleColor.Yellow;
break;
default:
Console.ForegroundColor = ConsoleColor.White;
break;
}
Console.Write(split[i]);
i++;
}
Console.WriteLine();
Console.ForegroundColor = def;
}
And test: EventManager.ColorizeConsoleMessage("&4Hello, &6world!");
Well you were a right the Regex.Matches & Regex.Split together were making things a little awkward, so i combined them
public static void ColorizeConsoleMessage(string message)
{
MatchCollection matches = Regex.Matches(message, "&+([0-9a-f])([^&]+)");
ConsoleColor def = Console.ForegroundColor;
foreach (Match match in matches)
{
switch (match.Groups[1].Value[0])
{
case '0':
Console.ForegroundColor = ConsoleColor.White;
break;
case '1':
Console.ForegroundColor = ConsoleColor.Gray;
break;
case '2':
Console.ForegroundColor = ConsoleColor.DarkGray;
break;
case '3':
Console.ForegroundColor = ConsoleColor.Black;
break;
case '4':
Console.ForegroundColor = ConsoleColor.Red;
break;
case '5':
Console.ForegroundColor = ConsoleColor.Green;
break;
case '6':
Console.ForegroundColor = ConsoleColor.Blue;
break;
case '7':
Console.ForegroundColor = ConsoleColor.Yellow;
break;
default:
Console.ForegroundColor = ConsoleColor.White;
break;
}
string str_to_print = match.Groups[2].Value;
Console.Write(str_to_print);
}
Console.WriteLine();
Console.ForegroundColor = def;
}