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.
- private void richTextBox1_TextChanged(object sender, EventArgs e)
- {
- string tokens = "(auto|double|int|struct|break|else|long|switch|case|
- enum|register|typedef|char|extern|return|union|const|
- float|short|unsigned|continue|for|signed|void|default|
- goto|sizeof|volatile|do|if|static|while)";
- Regex rex = new Regex(tokens);
- MatchCollection mc = rex.Matches(richTextBox1.Text);
- int StartCursorPosition = richTextBox1.SelectionStart;
- foreach (Match m in mc)
- {
- int startIndex = m.Index;
- int StopIndex = m.Length;
- richTextBox1.Select(startIndex, StopIndex);
- richTextBox1.SelectionColor = Color.Blue;
- richTextBox1.SelectionStart = StartCursorPosition;
- richTextBox1.SelectionColor = Color.Black;
- }
- }
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