2016-07-27 25 views
2

我有一個我使用的richTextBox,因此用戶可以看到他們擁有的XML文件並讓它們編輯它。我有一些代碼將關鍵字顏色更改爲我指定的顏色。這是我使用的方法:當點擊一個彩色字符串旁邊時,richtextbox讓我使用該顏色而不是黑色

private void CheckKeyword(string word, Color color, int startIndex) 
    { 
     if (this.richTextBox.Text.Contains(word)) 
     { 
      int index = -1; 
      int selectStart = this.richTextBox.SelectionStart; 
      while ((index = this.richTextBox.Text.IndexOf(word, (index + 1))) != -1) 
      { 
       this.richTextBox.Select((index + startIndex), word.Length); 
       this.richTextBox.SelectionColor = color; 
       this.richTextBox.Select(selectStart, 0); 
       this.richTextBox.SelectionColor = Color.Black; 
      } 
     } 
    } 

的問題是,當我點擊 near a coloured string,我開始輸入in that specific colour.

我知道爲什麼它的發生,但不知道如何解決它。

回答

0

您必須確定您的光標是否位於關鍵字區域的「內部」,或者不在KeyDown中,因此請連接KeyDown事件並嘗試使用此代碼。我確定有一種更有效的方式來確定您的光標是否在括號內的關鍵字內,但這似乎完成了工作:

void rtb_KeyDown(object sender, KeyEventArgs e) { 
    int openIndex = rtb.Text.Substring(0, rtb.SelectionStart).LastIndexOf('<'); 
    if (openIndex > -1) { 
    int endIndex = rtb.Text.IndexOf('>', openIndex); 
    if (endIndex > -1) { 
     if (endIndex + 1 <= this.rtb.SelectionStart) { 
     rtb.SelectionColor = Color.Black; 
     } else { 
     string keyWord = rtb.Text.Substring(openIndex + 1, endIndex - openIndex - 1); 
     if (keyWord.IndexOfAny(new char[] { '<', '>' }) == -1) { 
      this.rtb.SelectionColor = Color.Blue; 
     } else { 
      this.rtb.SelectionColor = Color.Black; 
     } 
     } 
    } else { 
     this.rtb.SelectionColor = Color.Black; 
    } 
    } else { 
    this.rtb.SelectionColor = Color.Black; 
    } 
} 
+0

謝謝!!!!這工作完美! – MosesTheHoly

相關問題