2010-10-21 47 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();  
}