2016-07-27 27 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

相关问题