我最近从这个链接 Color specific words in RichtextBox 发现了这段有趣的代码,它改变了 RichTextBox
控件中“关键词”的颜色。
问题是当单词的某些字母被删除时,单词仍然是彩色的。
例如。关键字是 AND 是红色的,但是如果我删除字母 N,剩下的字母 AD 仍然是红色。
我希望能够将其设置回 RichTextBox
ForeColor
。
我知道我应该在关键字检查之前将 ForeColor
设置回白色(我的默认颜色),但我尝试过的都没有用。
有什么想法吗?
代码 Sajeetharan
private void Rchtxt_TextChanged(object sender, EventArgs e)
{
this.CheckKeyword("and", Color.Red, 0);
this.CheckKeyword("or", Color.Red, 0);
}
private void CheckKeyword(string word, Color color, int startIndex)
{
if (this.Rchtxt.Text.Contains(word))
{
int index = -1;
int selectStart = this.Rchtxt.SelectionStart;
while ((index = this.Rchtxt.Text.IndexOf(word, (index + 1))) != -1)
{
this.Rchtxt.Select((index + startIndex), word.Length);
this.Rchtxt.SelectionColor = color;
this.Rchtxt.Select(selectStart, 0);
this.Rchtxt.SelectionColor = Color.Black;
}
}
}
最佳答案
您可以将完整文本的颜色重置为默认颜色(在本例中为黑色),然后运行您常用的关键字着色以再次应用颜色。
private void Rchtxt_TextChanged(object sender, EventArgs e)
{
this.CheckKeyword(Rchtxt.Text, Color.Black, 0);
this.CheckKeyword("and", Color.Red, 0);
this.CheckKeyword("or", Color.Red, 0);
}
关于c# - RichTextBox 从删除的 'keywords' 中移除颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50222406/