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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With