c# - RichtextBox 中的颜色特定单词

标签 c# winforms

我怎样才能做到,当用户在富文本框中键入“while”或“if”等特定词时,这些词会毫无问题地变成紫色?我试过不同的代码,但没有一个可用。代码如下:

if (richTextBox.Text.Contains("while"))
  {
    richTextBox.Select(richTextBox.Text.IndexOf("while"), "while".Length);
    richTextBox.SelectionColor = Color.Aqua;
  }

此外,我希望当用户删除该词或从该词中删除一个字母时,该词的颜色将恢复为默认颜色。我正在制作一个带有代码编辑器的程序。

我正在使用 Visual C#。

谢谢。

最佳答案

将事件添加到您的丰富框文本已更改,

  private void Rchtxt_TextChanged(object sender, EventArgs e)
        {
            this.CheckKeyword("while", Color.Purple, 0);
            this.CheckKeyword("if", Color.Green, 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;
            }
        }
    }

关于c# - RichtextBox 中的颜色特定单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21980554/

相关文章:

c# - CommandConverter 无法从 WPF 中的 System.String 转换

c# - 为什么 'foo' 返回空主体?

c# - 尝试创建开始最小化的表单时出现 StackOverflowException

c# - 如何检测所有者表单何时从内部控件关闭?

C# 拆分字符串并在 If 语句中使用

c# - 在 Word 文档中编辑 Excel 电子表格对象(C# Interop)

vb.net - 单击选项卡控件的选项卡,我想在 VB.Net 中执行操作

c# - 如何仅使用一个上下文菜单从不同的标签复制文本

c# - Linq DataTable 和 Take 方法

c# - SQLite 自动递增从 0 开始,然后进程终止