IntroductionThis article shows how to perform basic syntax highlighting using the RichTextBox control and C#.The example shows how to apply highlighting as text is loaded into the RichTextBox.Another article Part 2 will show you how to do this interactively as the user enters in text.For this example, the language to be syntax highlighted within the RichTextBox control is C#.
Description
In this example, I take you through the following steps:
Lets begin with creating a normal RichTextBox control like so.
Note, I define the RichTextBox control as a class variable so I can access it from other methods within the same class. This isnt shown here.
RichTextBox m_rtb =
String inputLanguage = "// Comment.\n" +"using System;\n" + "\n" +"public class Stuff : Form { \n" +" public static void Main(String args) {\n" +" }\n" + "}\n" ;
Then we can use the Regex class to split the input language into individual lines like so.
Regex r =
Next the contents of the input line are split into multiple tokens using the Regex class. The group syntax () is used to pull out the tokens including the delimiters. Then each token is examined to see whether it is a keyword or not. Before the text is added to the RichTextBox we must set the color and font of the text using the RichTextBox properties SelectionColor and SelectionFont. After this we can simply add the text tokens to the RichTextBox using the property SelectedText which acts like an append text function. The text tokens will now be displayed in the color and font we select.
Note, I have removed the code to detect comments // since it makes the code look cleaner. See the attached file for a more complete example.
void
Conclusion
This article described a rudimentary example of how to perform syntax highlighting as text is loaded into the RichTextBox control. A more thorough implementation is left to the reader. A second article will describe how to perform syntax highlighting interactively as the user enters in text.