Quick and easy custom syntax highlighting in a WinForms text box
A look at how to use the FastColoredTextBox library to get quick and easy WinForms syntax highlighting.

Some of the consultants (mining industry experts - not programmers) at my company were recently working on building some templates for our business rule engine. The templates are a strange mash-up of XML and mustache. This was obviously a daunting task, but it was decided that some decent syntax highlighting would greatly improve their productivity (and let them retain their sanity!).

WinForms is my go-to technology for quick-and-dirty GUIs, but there's no nice way of getting syntax highlighting in the default controls. Sure, you can do some nasty stuff to the RichTextBox control, but it's slow, ugly, and leaves you wanting to take a shower after writing the code.

Luckily, Pavel Torgashov's FastColoredTextBox provides an escape from this drudgery. Implementing syntax highlighting is as easy as overriding the textbox's TextChanged event and hooking up some styles to some regular expressions.

FontStyle style = FontStyle.Regular;
TextStyle blue = new TextStyle(Brushes.LightBlue, null, style);
TextStyle red = new TextStyle(Brushes.Red, null, style);
TextStyle green = new TextStyle(Brushes.Green, null, style);

void textBox_TextChanged(object sender, TextChangedEventArgs e)
{
    e.ChangedRange.ClearStyle(blue, red, green);
    e.ChangedRange.SetStyle(blue, "<.*?>");
    e.ChangedRange.SetStyle(red, "{{(?!!)(?!GUID).*?}}");
    e.ChangedRange.SetStyle(green, "{{! .*? }}");
}

The final result: a handy syntax-highlighting editor, all in a few minutes of work!


Posted by Matthew King on 11 January 2014
Permission is granted to use all code snippets under CC BY-SA 3.0 (just like StackOverflow), or the MIT license - your choice!
If you enjoyed this post, and you want to show your appreciation, you can buy me a beverage on Ko-fi or Stripe