RichtextBox中的颜色​​特定词 [英] Color specific words in RichtextBox

查看:101
本文介绍了RichtextBox中的颜色​​特定词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能让,当用户键入特定的词像'而'或者'如果'在一个富有的文本框,言紫色没有任何问题?我试过不同势码,但他们都不是可用的。这些代码就像如下:

How can I make, that when the user types specific words like 'while' or 'if' in a rich textbox, the words will color purple without any problems? I've tried diffrent codes, but none of them were usable. The codes were like below:

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



另外,我想,当用户删除单词或删除的一封信这个词,这个词将颜色恢复到默认的颜色。我正在用它的代码编辑器的程序。

Also, I want that when the user removes the word or removes a letter from the word, the word will color back to its default color. I'm making a program with a code editor in it.

我使用的Visual C#。

I am using Visual c#.

感谢你。

推荐答案

这是添加连你的丰富框中的文本改变了,

Add an even to your rich box text changed,

  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;
            }
        }
    }

这篇关于RichtextBox中的颜色​​特定词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆