Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

I want to create a simple editor like Notepad++ with simple functionality... I need to color a specific word in the rich text box area. How can I do that?

For example: when the user write these word, I want to color them to the blue color. These words are: for, while, if, try, etc.

How can I make the richtextbox to select a specific word and then color them? And, if I want to make a comment and color everything after the //, how is that done in the richtextbox?

How do I number the line in the text box, so I can now the line number when I'm coding in my editor?

like image 431
Q8Y Avatar asked Sep 14 '10 08:09

Q8Y


2 Answers

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.

like image 193
Alex Essilfie Avatar answered Oct 03 '22 22:10

Alex Essilfie


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.

like image 28
VinayC Avatar answered Oct 03 '22 22:10

VinayC