C# School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

Welcome to Dream.In.Code
Become a C# Expert!

Join 307,221 C# Programmers for FREE! Get instant access to thousands of C# experts, tutorials, code snippets, and more! There are 1,673 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: 997
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

jammmie999
*



post 17 May, 2009 - 12:10 AM
Post #4
QUOTE(gabehabe @ 24 Sep, 2008 - 02:39 PM) *

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

Hi when I try and add
CODE
        [DllImport("user32.dll")] // import lockwindow to remove flashing
        public static extern bool LockWindowUpdate(IntPtr hWndLock);

I get an error message:
Error 1 Expected class, delegate, enum, interface, or struct
Error 2 The modifier 'extern' is not valid for this item

What is wrong

Thanks
Go to the top of the page
+Quote Post

Ändrew
Group Icon



post 27 May, 2009 - 10:16 PM
Post #5
QUOTE(jammmie999 @ 17 May, 2009 - 06:10 PM) *

Hi when I try and add
CODE
        [DllImport("user32.dll")] // import lockwindow to remove flashing
        public static extern bool LockWindowUpdate(IntPtr hWndLock);

I get an error message:
Error 1 Expected class, delegate, enum, interface, or struct
Error 2 The modifier 'extern' is not valid for this item

What is wrong

Thanks


CODE
using System.Runtime.InteropServices;


Make sure you have that...
Go to the top of the page
+Quote Post

thaproxinator
*



post 24 Jun, 2009 - 10:34 AM
Post #6
hi, i am currently using this code in vb.net and am wondering if single characters can be highlighted e.g. ">"

i have tried to do this but it just highlights the whole text in the RichTextBox

any help would be appreciated

tia

EDIT: nevermind, my code was wrong. i managed to fix it

This post has been edited by thaproxinator: 25 Jun, 2009 - 04:04 AM
Go to the top of the page
+Quote Post

tuyen
*



post 10 Aug, 2009 - 09:22 PM
Post #7
Dear !
I am trying implement "highlight" method to above Web Browser. I desire to add a button that when it is clicked, selected text on Browser will will be highlighted. But i don't know how to do. Could some one help me smile.gif !

Thank you very much !
Go to the top of the page
+Quote Post

CheckersW
Group Icon



post 21 Aug, 2009 - 02:44 AM
Post #8
QUOTE(tuyen @ 10 Aug, 2009 - 09:22 PM) *

Dear !
I am trying implement "highlight" method to above Web Browser. I desire to add a button that when it is clicked, selected text on Browser will will be highlighted. But i don't know how to do. Could some one help me smile.gif !

Thank you very much !


Instead of asking for help here, you should start a new topic in the forums and just include a link to the page there. That way, more people will see your question and help you, and others will be able to learn from the answer to your question more easily.
Go to the top of the page
+Quote Post

binary_refinary
*



post 7 Nov, 2009 - 01:45 AM
Post #9
Hey,

many thanks for the quick tutorial !

hands down- the best tutor i've found on the net for c# text highlighting smile.gif
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: 11/21/09 10:40PM

Live C# Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

C# Tutorials

Reference Sheets

C# Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month