Full Version: Syntax Highlight in C#
Dream.In.Code > Programming Tutorials > C# Tutorials
PixelCard
In this tutorial you will see how to implement the syntax highlighting feature in a C# WinForms application. For this purpose I will use the RegularExpressions class, member of the System.Text namespace.

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:

IPB Image

2. Add a RichTextBox control to the form:

IPB Image

3. Add a Timer control to the form:

IPB Image

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;
}
}


gabehabe
Nice tutorial! I just wish I could've found it before I wrote 500 lines of a class to do it sleep.gif
Then again, my class deals with comments and block comments, too smile.gif

Two things though:
When it highlights the text, it's going to flash, isn't it?

Why not block that out with LockWindowUpdate() ?

csharp
[DllImport("user32.dll")] // import lockwindow to remove flashing
public static extern bool LockWindowUpdate (IntPtr hWndLock);


Then, in your TextChanged event, you could do the following:
csharp
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
try {
LockWindowUpdate(richTextBox1.Handle);
//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;
}
} finally {LockWindowUpdate(IntPtr.Zero);}
}


Also, with longer code, it could start to take a while. That could be fixed by working word for word. (Just read back to find the most recent space)

smile.gif
TonicX57
Nice. Thanks a lot for this tutorial. This really helps. I was trying to make an editor for my programming language, but I couldn't figure out how. Thanks, mate.
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2008 Invision Power Services, Inc.