우울하지만 단순한 해결책.
전경색 태그 시작 : <*color*>
. 전경색 태그의 끝 : <*/*>
. 배경색 태그 시작 : <*!color*>
. 배경색 태그 끝 : <*/!*>
.
사용 예 : 허용 색상의
WriteLineColor("<*!red*><*yellow*>Yellow text<*/*> and <*cyan*>cyan text<*/*> on red background.<*/!*>");
목록 (시스템.검은 색, 진한 파란색, 다크 그린, 다크 시안, 다크 레드, 다크 매젠타, 다크 옐로우, 그레이, 다크 그레이, 블루, 그린, 시안, 레드, 마젠타, 옐로우, 화이트.
static void WriteColor(string str)
{
var fgStack = new Stack<ConsoleColor>();
var bgStack = new Stack<ConsoleColor>();
var parts = str.Split(new[] { "<*" }, StringSplitOptions.None);
foreach (var part in parts)
{
var tokens = part.Split(new[] { "*>" }, StringSplitOptions.None);
if (tokens.Length == 1)
{
Console.Write(tokens[0]);
}
else
{
if (!String.IsNullOrEmpty(tokens[0]))
{
ConsoleColor color;
if (tokens[0][0] == '!')
{
if (Enum.TryParse(tokens[0].Substring(1), true, out color))
{
bgStack.Push(Console.BackgroundColor);
Console.BackgroundColor = color;
}
}
else if (tokens[0][0] == '/')
{
if (tokens[0].Length > 1 && tokens[0][1] == '!')
{
if (bgStack.Count > 0)
Console.BackgroundColor = bgStack.Pop();
}
else
{
if (fgStack.Count > 0)
Console.ForegroundColor = fgStack.Pop();
}
}
else
{
if (Enum.TryParse(tokens[0], true, out color))
{
fgStack.Push(Console.ForegroundColor);
Console.ForegroundColor = color;
}
}
}
for (int j = 1; j < tokens.Length; j++)
Console.Write(tokens[j]);
}
}
}
static void WriteLineColor(string str)
{
WriteColor(str);
Console.WriteLine();
}
static void WriteColor(string str, params object[] arg)
{
WriteColor(String.Format(str, arg));
}
static void WriteLineColor(string str, params object[] arg)
{
WriteColor(String.Format(str, arg));
Console.WriteLine();
}
단 하나의 색상이있는 선에 대해 쓸 코드가 많이 있습니다. 나는 이것을 단순화하는 방법을 궁금해했다. 그래서 모든 줄을 다시 한번 타이핑 할 필요없이 내 전체 프로그램을 통해 그 색상을 사용할 수있다. – Chris
@Chris : 요점은 한 번만 해당 메서드를 작성한 다음 여러 번 호출해야한다는 것입니다. 아마도 프로그램 전체에 코드를 작성하는 방법을 보여 줄 수 있다면 도움이 될 것입니다. –
Chris, 작성 방법 : ColoredConsoleWrite (Color.Red, "blah"); 너무 복잡하고/너무 길어? – rochal