How to select text from the RichTextBox and then color it?

Here's some code you can build on in order to achieve the functionality you want.

private void ColourRrbText(RichTextBox rtb)
{
    Regex regExp = new Regex("\b(For|Next|If|Then)\b");

    foreach (Match match in regExp.Matches(rtb.Text))
    {
        rtb.Select(match.Index, match.Length);
        rtb.SelectionColor = Color.Blue;
    }
}

The CodeProject article Enabling syntax highlighting in a RichTextBox shows how to use RegEx in a RichTextBox to perform syntax highlighting. Specifically, look at the SyntaxRichtTextBox.cs for the implementation.


In general, you have to work on the selection in RichTextBox. You can manipulate the current selection using the Find method or using SelectionStart and SelectionLength properties. Then you can change properties of selected text using SelectionXXX properties. For example, SelectionColor would set the color of current selection, etc. So you have to parse text in richtextbox and then select part of texts and change their properties as per your requirements.

Writing a good text editor using RichTextBox can be quite cumbersome. You should use some library such as Scintilla for that. Have a look at ScintillaNet, a .NET wrapper over Scintilla.


Did you know that Notepad++ uses Scintilla?

You actually do not have to reinvent the wheel by going through all the trouble as there is a .NET port of Scintilla named ScintillaNET which you can freely embed in your application as the source code editor :)

But to answer your question, there are few parts that you need to understand

  1. Finding what to color
  2. When to color
  3. How to color

  4. For the first part, there may be different approaches, but I think using regular expressions would be a good choice. I am sorry, but I don't know regular expressions much so I cannot help you in that case.

  5. When to color is very crucial and if you do it wrong, your application will suffer a heavy performance penalty. I suggest you refer to XPath Visualizer which was done by our own Stack Overflow member, Cheeso. Take a look at the source on how the coloring of the syntax was done. But if you ScintillaNET, everything would be taken care of. Anyway, I really can't seem to find this documentation where he clearly showed how the coloring of the text was done. I would most definitely post it here if I find it.

  6. The third question I think is covered by VinayC. But basically you use SelectionColor along with SelectionStart.

Tags:

C#