Syntax Highlighting in a RichTextBox

Posted on May 18, 2009. Filed under: .net, c#, WinForms | Tags: , , |

Rich Text Box control is one of the best controls from which we can derive multiple uses. One such usage is building a code editor. Let me take SQL for example as the language I want to code in. It looks good to see keywords in different color than my normal text. It gives me the visual effect that can definitely improve my productivity.

Recently I also got to do some thing like this, where in I was asked to build a Rich Text Box which can colorize the text as you type in. Interesting stuff.

I started with trying to handle the TextChanged event and colorizing the text, but it didn’t turned out as expected. As I type and if word matches for colorization, it gets colored but since I keep typing that words get replace with my new text. Pretty bad. Huh! Well! Then I tried to understand the windows messaging model behind the scene of the TextChanged event and understood that till I complete the colorization, any new messages should be locked for processing. This way I reached the output I wanted to reach.

Below is the code you need to start with…you can enhance the code as per your needs.

Create a new class, lets name it SyntaxRTB, and derive it from RichTextBox class

class SyntaxRTB: System.Windows.Forms.RichTextBox
{
 [DllImport("user32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
 private static extern int LockWindowUpdate(int hWnd);

 protected override void OnTextChanged(System.EventArgs e)
 {
 base.OnTextChanged(e);
 ColorTheKeyWords();
}

private void ColorTheKeyWords()
{
 int SelectionAt = this.SelectionStart;
 LockWindowUpdate(this.Handle.ToInt32());
 Match m = Regex.Match(this.Text, "\\b(select)\\b", RegexOptions.IgnoreCase);
 if (m.Success)
 {
 this.SelectionStart = m.Index;
 this.SelectionLength = m.Length;
 this.SelectionColor = Color.Blue;
 }
 this.SelectionStart = SelectionAt;
 this.SelectionLength = 0;
 this.SelectionColor = Color.Black;

LockWindowUpdate(0);
}
}

Compile your code and start using the new Rich Text Box.

The key here is, as soon as the Text Changes we should stop Windows from sending a message otherwise it will affect the next keystroke and the next keystroke will erase the word being formatted. So once our formatting is completed, we unlock the update and this way our next keystroke gets processed normally.

One more thing is, always use Regular Expressions to match your words for coloring. This is because of performance and even perfect text matching.

I have shown only one key word (Select) here to demonstrate the syntax coloring. You can build from here on and keep a list of keywords to color and may be use different color for each word.

Possibilities are unlimited. Happy Coding!

Make a Comment

Leave a comment

Liked it here?
Why not try sites on the blogroll...