2011-07-18 160 views
2

用戶類型我想創建一個簡單的文本編輯器,但支持彩色字體像「編譯」更改字體顏色爲RichTextBox的

假設我的程序的關鍵字是「狗」,「牛」,「貓」 ,「鳥」

我有一個RichTextBox實現TextChanged事件。

現在,我的問題是我不知道如何在遇到關鍵字時更改字體顏色。

例字符串:A Big Dog and a Cat

狗將顏色紅色,而貓將是綠色。

+1

只需檢查一下http://www.codeproject.com/KB/edit/SyntaxRichTextBox.aspx – V4Vendetta

回答

0

我不知道這將是多麼有效,當你有大量的文本,但它的作品相當不錯,我已經測試它。

private void CheckKeyword(string word, Color color, int startIndex) 
{ 
    if (this.richTextBox1.Text.Contains(word)) 
    { 
     int index = -1; 
     int selectStart = this.richTextBox1.SelectionStart; 

     while ((index = this.richTextBox1.Text.IndexOf(word, (index + 1))) != -1) 
     { 
      this.richTextBox1.Select((index + startIndex), word.Length); 
      this.richTextBox1.SelectionColor = color; 
      this.richTextBox1.Select(selectStart, 0); 
      this.richTextBox1.SelectionColor = Color.Black; 
     } 
    } 
} 

private void richTextBox1_TextChanged(object sender, EventArgs e) 
{ 
    this.CheckKeyword("dog", Color.Red, 0); 
    this.CheckKeyword("cat", Color.Green, 0); 
}