Color specific words in RichtextBox

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

This is something that you can do, I would recommend using a regular expression to find all matches of the word in case it occurs many times. Also keep in mind that the string find could be a list of strings out side of a for loop to consider multiple words but this should get you started.

//dont foget to use this at the top of the page
using System.Text.RegularExpressions;

    private void richTextBox1_TextChanged(object sender, EventArgs e)
    {
        string find = "while";
        if (richTextBox1.Text.Contains(find))
        {
            var matchString = Regex.Escape(find);
            foreach (Match match in Regex.Matches(richTextBox1.Text, matchString))
            {
            richTextBox1.Select(match.Index, find.Length);
            richTextBox1.SelectionColor = Color.Aqua;
            richTextBox1.Select(richTextBox1.TextLength, 0);
            richTextBox1.SelectionColor = richTextBox1.ForeColor;
            };
        }
    }

Tags:

C#

Winforms