2015-09-28 37 views
0

我想更改等號的顏色,因爲它在用戶寫入文本時發生在記事本++中。我的代碼正在工作,但光標停留在一個地方,用戶不能在文本之間寫入任何內容,只允許在最後寫入文本,也不會在=後出現新行。怎麼做 ?如何更改richtextbox中等號的顏色c#

private void richTextBox1_KeyPress(object sender, KeyPressEventArgs e) 
{ 
    equal();  
} 

public void equal() 
{ 
    start = richTextBox1.Text.Length - 1; 
    length = 1; 

    richTextBox1.SelectionStart = start; 
    richTextBox1.SelectionLength = length; 
    string settext = richTextBox1.SelectedText; 

    if (settext ==Convert.ToString('=')) 
    { 
     richTextBox1.SelectionColor = Color.Purple; 
    } 
} 

回答

1
Add event to your richtext box for text changed: 

private void richTextBox1_TextChanged(object sender, EventArgs e) 
    { 
     this.ChangeColor("=", Color.Purple); 

    } 



private void ChangeColor(string word, Color color) 
{ 
    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), word.Length); 
      this.richTextBox1.SelectionColor = color; 
      this.richTextBox1.Select(selectStart, 0); 
      this.richTextBox1.SelectionColor = Color.Black; 
     } 
    } 
} 
+0

謝謝!很多@amitdayam – phpnet

1

請使用richTextBox_TextChanged事件改變顏色。我在應用程序中遇到過這個問題。