Search code examples
c#winformscolorsrichtextbox

RichTextBox remove color from deleted 'keywords'


I've recently found this interesting code that changes the color of the 'key words' in a RichTextBox control, from this link Color specific words in RichtextBox

The problem is that when some letters of the word are deleted, the word is still colored.

eg. keyword is AND and it is red, but if i delete letter N, the remaining letters AD are still red.

I want to able to set it back to the RichTextBox ForeColor.

I know that I should probably set the ForeColor back to white (my default color) before the keywords check, but nothing I tried is working.

Any ideas?

Code by Sajeetharan

private void Rchtxt_TextChanged(object sender, EventArgs e)
    {
        this.CheckKeyword("and", Color.Red, 0);
        this.CheckKeyword("or", Color.Red, 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;
        }
    }
}

Solution

  • You can reset the color of complete text to the default color (black in this case) and then run your usual keyword coloring to apply the colors again.

        private void Rchtxt_TextChanged(object sender, EventArgs e)
        {
            this.CheckKeyword(Rchtxt.Text, Color.Black, 0);
            this.CheckKeyword("and", Color.Red, 0);
            this.CheckKeyword("or", Color.Red, 0);
        }