c# - RichTextBox 从删除的 'keywords' 中移除颜色

标签 c# winforms colors richtextbox

我最近从这个链接 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/

相关文章:

c# - LINQ 值查询返回错误的字符串

c# - 停止任务栏闪烁

android - 在 21 android 以下的 api 上更改状态/通知栏颜色?

android - 如何获取 Canvas 像素

c# - Entity Framework 代码优先 - 不支持索引属性

c# - 在 .NET/C# 上下文中,什么是二分搜索以及如何/为什么使用二分搜索?

c# - 无法进行简单的 enyim memcached 测试或 log4net 工作

c# - .NET 条码扫描器 DeviceEnabled 的 POS 设置失败

c# - 如何在 PropertyGrid 中显示对象的 "Value"属性

python - 用python绘制不同颜色的圆圈