Special Tutorial Requirements:
- C# IDE (Visual Studio 2008 used in this tutorial)
- .NET Framework 1.0
So, here we go.
1. Create a C# Windows Forms application:

2. Add a RichTextBox control to the form:

3. Add a Timer control to the form:

4. Change the following timer properties:
- Enabled = True
- Interval = 1000
5. Add the System.Text.RegularExpressions namespace to the project:
csharp
using System.Text.RegularExpressions;
6. Create a new regex right after "public partial class Form1 : Form {". I will name it keyWords:[b]
csharp
public Regex keyWords = new Regex& quot;abstract|as|base|bool|break|byte|case|catch|char|checked|class|const|contin
ue|decimal|default|delegate|do|double|else|enum|event|explicit|extern|false|fina
lly|fixed|float|for|" +
& quot;foreach|goto|if|implicit|in|int|interface|internal|is|lock|long|namespace|n
ew|null|object|operator|out|override|params|private|protected|public|readonly|re
f|return|sbyte|sealed|short|sizeof|stackalloc|static|" + & quot;string|struct|switch|this|throw|true|try|typeof|uint|ulong|unchecked|unsafe
|ushort|using|virtual|volatile|void|while|");
My regex contains all C# reserved words from this MSDN page:
C# Keywords
[b]7. This code goes for the timer (timer1_Tick):
csharp
private void timer1_Tick(object sender, EventArgs e)
{
//Highlight every found word from keyWords.
//Get the last cursor position in the richTextBox1.
int selPos = richTextBox1.SelectionStart;
//For each match from the regex, highlight the word.
foreach (Match keyWordMatch in keyWords.Matches(richTextBox1.Text))
{
richTextBox1.Select(keyWordMatch.Index, keyWordMatch.Length);
richTextBox1.SelectionColor = Color.Blue;
richTextBox1.SelectionStart = selPos;
richTextBox1.SelectionColor = Color.Black;
}
}
Of course you can add more regex variables for different words and different colors for highlighting.
Every 1 second the text will be parsed for matches and every found match will be highlighted. This code can be modified. Instead of using the timer's tick event the richTextBox's TextChanged event can be used. The code will look like this:
csharp
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
//Highlight every found word from keyWords.
//Get the last cursor position in the richTextBox1.
int selPos = richTextBox1.SelectionStart;
//For each match from the regex, highlight the word.
foreach (Match keyWordMatch in keyWords.Matches(richTextBox1.Text))
{
richTextBox1.Select(keyWordMatch.Index, keyWordMatch.Length);
richTextBox1.SelectionColor = Color.Blue;
richTextBox1.SelectionStart = selPos;
richTextBox1.SelectionColor = Color.Black;
}
}