Welcome to Dream.In.Code
Getting C# Help is Easy!

Join 136,857 C# Programmers for FREE! Get instant access to thousands of C# experts, tutorials, code snippets, and more! There are 1,611 people online right now. Registration is fast and FREE... Join Now!




Syntax Highlight in C#

 
Reply to this topicStart new topic

> Syntax Highlight in C#, How to implement syntax highlighting in a WinForms application.

PixelCard
Group Icon



post 9 Jul, 2008 - 08:43 AM
Post #1


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




Attached File(s)
Attached File  syntaxHighlight.zip ( 39.31k ) Number of downloads: 156
Go to the top of the page
+Quote Post


Register to Make This Ad Go Away!

gabehabe
Group Icon



post 24 Sep, 2008 - 02:39 PM
Post #2
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
Go to the top of the page
+Quote Post

TonicX57
**



post 16 Nov, 2008 - 12:13 PM
Post #3
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.
Go to the top of the page
+Quote Post


Fast ReplyReply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 

Lo-Fi Version Time is now: 12/3/08 06:50PM

Live C# Help!

C# Tutorials

Reference Sheets

C# Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month