Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

I am using Visual c#.

Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
339 views
Welcome To Ask or Share your Answers For Others

1 Answer

Add an event 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;
            }
        }
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...