2012-10-15 73 views
0

可能重複:
How do i color a specific part of text in a richTextBox?如何爲richTextBox中的不同文本着色?

我有這樣的功能:

private void richTextBoxLoadKeys(Dictionary<string, List<string>> dictionary, string FileName) 
     { 
      string line = System.String.Empty; 
      using (StreamReader sr = new StreamReader(keywords)) 
      { 
       while ((line = sr.ReadLine()) != null) 
       { 
        string[] tokens = line.Split(','); 
        dictionary.Add(tokens[0], tokens.Skip(1).ToList()); 
        richTextBox2.AppendText("Url: " + tokens[0] + " --- " + "Localy KeyWord: " + tokens[1]+Environment.NewLine); 
        AppendText(richTextBox2, "Url: ", Color.Red); 
       } 
       sr.Close(); 
      } 
     } 

和我有功能AppendText通過:

public void AppendText(RichTextBox box, string text, Color color) 
     { 
      box.SelectionStart = box.TextLength; 
      box.SelectionLength = 0; 
      box.SelectionColor = color; 
      box.AppendText(text); 
      box.SelectionColor = box.ForeColor; 
     } 

在RichTextBox的我有例如:

Url: http://www.google.com --- Localy KeyWord: google 
Url: http://www.cnet.com --- Localy KeyWord: cnet 
Url: http://www.g.com --- Localy KeyWord: g 

結果時試圖將其顏色爲紅色的是,所述第一地址:是在黑則兩個後它是在紅色,然後在端部其添加只有Url的新行:in Red。

我想要做的是在紅色的Url中着色:它自己的鏈接在黃色---在綠色的localy關鍵字:在粉紅色和谷歌或cnet或g在藍色。

我希望每行中的文本的每個部分都處於另一種顏色。

解決它:

void AppendText() 
     { 

      int len = this.richTextBox2.TextLength; 
      int index = 0; 
      int lastIndex = this.richTextBox2.Text.LastIndexOf("Url: "); 

      while (index < lastIndex) 
      { 
       this.richTextBox2.Find("Url: ", index, len, RichTextBoxFinds.None); 
       this.richTextBox2.SelectionColor = Color.Red; 
       index = this.richTextBox2.Text.IndexOf("Url: ", index) + 1; 
      } 
     } 
+2

Dup的http://stackoverflow.com/questions/12854031/how-do-i-color-a-specific-part-of-text-的in-a-richtextbox/12854129#12854129你已經做了完全相同的錯誤,作爲該問題的海報 – BugFinder

+0

它是在勝利形式或網絡???????? \ –

+0

Win-Forms它是 – user1741587

回答

0

你得叫你Select設置SelectionColor之前。以下是示例代碼。

box.Select(0, 10); 
box.SelectionColor = color; 
+0

找到的解決方案將更新我的問題。 – user1741587

+0

我應該回答我自己的問題還是等待某人回答並標記它? – user1741587

+0

@ user1741587 *您*作爲OP,需要接受答案...閱讀常見問題解答! –

0

這個解決它:

void AppendText(string text,Color color) 
     { 

      int len = this.richTextBox2.TextLength; 
      int index = 0; 
      int lastIndex = this.richTextBox2.Text.LastIndexOf(text); 

      while (index < lastIndex) 
      { 
       this.richTextBox2.Find(text, index, len, RichTextBoxFinds.None); 
       this.richTextBox2.SelectionColor = color; 
       index = this.richTextBox2.Text.IndexOf(text, index) + 1; 
      } 
     }