2010-10-21 46 views
1

嗨我试图添加一些颜色到这个字符串为一个简单的控制台应用程序即时创建。 我希望每封信都有不同的颜色。C#控制台字符串生成器与前景色

const string WelcomeMessage =  @" _______ _ _______  _______" + NewLine + 
            @"|__ __(_) |__ __| |__ __| " + NewLine + 
            @" | | _ ___| | __ _ ___| | ___ __" + NewLine + 
            @" | | | |/ __| |/ _` |/ __| |/ _ \/_ \ " + NewLine + 
            @" | | | | (__| | (_| | (__| | (_) | __/ " + NewLine + 
            @" |_| |_|\___|_|\__,_|\___|_|\___/ \___| " 

我知道我可以只使用

Console.ForegroundColor = ConsoleColor.Blue; 
Console.Write(" _______"); 

,然后写这封信的每一个部分,但是这将让我的代码几乎是不可能的阅读和维护。 所以我只想知道是否存在某种类型的StringBuilder设计用于控制台输出,其中可能包括foregroundColor信息。

+2

我没有回答您的问题,但我确实收到了一条提示来清理您的字符串。将@添加到字符串文字的开头时,您可以通过换行符继续该字符串。所以字符串hw = @“你好 世界”;将有NewLine。尔加!评论不允许换行格式。我试图在Hello和World之间输入
。 – Kleinux 2010-10-21 12:57:03

回答

1

我怀疑是否有任何知名的API。但是你可以创建一个标记每个字母的矩形列表。下面的示例演示了前三个字母:

static void Main(string[] args) 
{ 
    string WelcomeMessage = 
           @" _______ _ _______  _______   " + Environment.NewLine + 
           @"|__ __(_) |__ __| |__ __|   " + Environment.NewLine + 
           @" | | _ ___| | __ _ ___| | ___ __ " + Environment.NewLine + 
           @" | | | |/ __| |/ _` |/ __| |/ _ \/_ \ " + Environment.NewLine + 
           @" | | | | (__| | (_| | (__| | (_) | __/ " + Environment.NewLine + 
           @" |_| |_|\___|_|\__,_|\___|_|\___/ \___| "; 

    List<Rectangle> list = new List<Rectangle>(); 
    list.Add(new Rectangle(new Point(0, 0), new Size(7, 6))); 
    list.Add(new Rectangle(new Point(8, 0), new Size(2, 6))); 
    list.Add(new Rectangle(new Point(10, 2), new Size(4, 4))); 

    Dictionary<Rectangle, ConsoleColor> colors = new Dictionary<Rectangle, ConsoleColor>(); 
    colors.Add(list[0], ConsoleColor.DarkBlue); 
    colors.Add(list[1], ConsoleColor.DarkRed); 
    colors.Add(list[2], ConsoleColor.DarkGreen); 
    Console.WriteLine(WelcomeMessage); 

    // NOTE: you might want to save the lines in an array where you define it: 
    string[] lines = WelcomeMessage.Split(new string[] { Environment.NewLine }, StringSplitOptions.None); 
    for (int y = 0; y < lines.Length; y++) 
    { 
    string line = lines[y]; 
    for (int x = 0; x < line.Length; x++) 
    { 
     Rectangle rect = list.Where(c => 
     x >= c.X && x <= c.X + c.Width && 
     y >= c.Y && y <= c.Y + c.Height).FirstOrDefault(); 

     if (rect == Rectangle.Empty) 
     break ; // TODO Not implemented yet   
     else 
     {    
     Console.ForegroundColor = colors[rect]; 
     Console.Write(line[x]); 
     } 
    } 
    Console.WriteLine(); 
    } 

    Console.ReadKey();  
}