c# - 当用户在 RichTextBox 中键入时更改字体颜色

标签 c# .net winforms richtextbox

我想创建一个简单的文本编辑器,但像“编译器”一样支持多色字体

假设我的程序关键字是:“狗”,“牛”,“猫”,“鸟”

我有一个实现 TextChanged 事件的 RichTextBox。

现在,我的问题是我不知道如何在遇到关键字时更改字体颜色。

示例字符串:一只大狗和一只猫

狗是红色的,而猫是绿色的。

最佳答案

我不确定当你有大量文本时这会有多有效,但在我测试过的范围内它工作得相当好。

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

private void richTextBox1_TextChanged(object sender, EventArgs e)
{
    this.CheckKeyword("dog", Color.Red, 0);
    this.CheckKeyword("cat", Color.Green, 0);
}

关于c# - 当用户在 RichTextBox 中键入时更改字体颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6729787/

相关文章:

c# - 如何使用 LIKE 关键字简化或重写 Cosmos 查询

c# - 如何保留/存储我的 Azure 凭据?

c# - 用户名认证网络服务

c# - async/await 方法中的耗时任务

c# - ComboBox items.count 与数据源不匹配

c# - 在网格 C# 中显示完整的日期时间

c# - 在类中包装一个简单类型有什么好处?

c# - 添加一批实体。如何确定调用 SaveChanges() 时哪些实体失败

winforms - Windows 窗体应用程序的物理中间层分离

c# - 如何将.Net3.5 dll 添加到.Net2.0 工程中?