Syntax Highlighting in RichTextBox using C#

When we make an application like programming editor for language it provides syntax highlighting that makes the user comfortable to work with it as everybody likes colored text that can be easy to read and distinguish between normal variable names and language keywords.
In this I will show you how provide such syntax highlighting feature in RichTextBox control.
It's simple to make it.
Drag a RichTextBox control on the form.. Now we need when user types text it should be highlighted if its keyword of language. I will use Blue color here to highlight the keyword of language.
Now to make this feature available to user we need a collection of all keywords of language. So here in demonstration, I'm making syntax highlighting for C language so I need C language Keyword list...
I acquired all from here
Now think about how we should update the color of text obviously it would be nice if we update color of text to blue as we type in RichTextBox. So we will write code in RichTextBox's text changed event.
  1. private void richTextBox1_TextChanged(object sender, EventArgs e)  
  2. {  
  3.     string tokens = "(auto|double|int|struct|break|else|long|switch|case|  
  4.                               enum|register|typedef|char|extern|return|union|const|  
  5.                              float|short|unsigned|continue|for|signed|void|default|  
  6.                               goto|sizeof|volatile|do|if|static|while)";  
  7.     Regex rex = new Regex(tokens);  
  8.     MatchCollection mc = rex.Matches(richTextBox1.Text);  
  9.     int StartCursorPosition = richTextBox1.SelectionStart;  
  10.     foreach (Match m in mc)  
  11.     {  
  12.         int startIndex = m.Index;  
  13.         int StopIndex = m.Length;  
  14.         richTextBox1.Select(startIndex, StopIndex);  
  15.         richTextBox1.SelectionColor = Color.Blue;  
  16.         richTextBox1.SelectionStart = StartCursorPosition;  
  17.         richTextBox1.SelectionColor = Color.Black;  
  18.     }  

You can see here in first line I have written all the keywords of C language that we want to highlight. Then I match collection and color them one by one by selecting it and change its font color.
And here is my result 
1.gif


Similar Articles