• (2 Pages)
  • +
  • 1
  • 2

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

#1 PixelCard  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 47
  • View blog
  • Posts: 139
  • Joined: 20-June 08

Posted 09 July 2008 - 09:43 AM

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:

Posted Image

2. Add a RichTextBox control to the form:

Posted Image

3. Add a Timer control to the form:

Posted Image

4. Change the following timer properties:
  • Enabled = True
  • Interval = 1000

5. Add the System.Text.RegularExpressions namespace to the project:

using System.Text.RegularExpressions;



6. Create a new regex right after "public partial class Form1 : Form {". I will name it keyWords:[b]

public Regex keyWords = new Regex"abstract|as|base|bool|break|byte|case|catch|char|checked|class|const|continue|decimal|default|delegate|do|double|else|enum|event|explicit|extern|false|finally|fixed|float|for|" +
"foreach|goto|if|implicit|in|int|interface|internal|is|lock|long|namespace|new|null|object|operator|out|override|params|private|protected|public|readonly|ref|return|sbyte|sealed|short|sizeof|stackalloc|static|" + "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):


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:

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)



Is This A Good Question/Topic? 4
  • +

Replies To: Syntax Highlight in C#

#2 gabehabe  Icon User is offline

  • GabehabeSwamp
  • member icon




Reputation: 1377
  • View blog
  • Posts: 10,951
  • Joined: 06-February 08

Posted 24 September 2008 - 03:39 PM

Nice tutorial! I just wish I could've found it before I wrote 500 lines of a class to do it -_-
Then again, my class deals with comments and block comments, too :)

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

Why not block that out with LockWindowUpdate() ?

[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:
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)

:)
Was This Post Helpful? 1
  • +
  • -

#3 TonicX57  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 84
  • Joined: 13-September 08

Posted 16 November 2008 - 01:13 PM

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.
Was This Post Helpful? 0
  • +
  • -

#4 jammmie999  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 117
  • Joined: 01-April 09

Posted 17 May 2009 - 01:10 AM

View Postgabehabe, on 24 Sep, 2008 - 02:39 PM, said:

Nice tutorial! I just wish I could've found it before I wrote 500 lines of a class to do it -_-
Then again, my class deals with comments and block comments, too :)

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

Why not block that out with LockWindowUpdate() ?

[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:
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)

:)

Hi when I try and add
		[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
Was This Post Helpful? 0
  • +
  • -

#5 Ändrew  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 25
  • View blog
  • Posts: 312
  • Joined: 21-April 08

Posted 27 May 2009 - 11:16 PM

View Postjammmie999, on 17 May, 2009 - 06:10 PM, said:

Hi when I try and add
		[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


using System.Runtime.InteropServices;


Make sure you have that...
Was This Post Helpful? 0
  • +
  • -

#6 thaproxinator  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 24-June 09

Posted 24 June 2009 - 11:34 AM

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 June 2009 - 05:04 AM

Was This Post Helpful? 0
  • +
  • -

#7 tuyen  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 04-August 09

Posted 10 August 2009 - 10: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 :) !

Thank you very much !
Was This Post Helpful? 0
  • +
  • -

#8 CheckersW  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 12
  • View blog
  • Posts: 198
  • Joined: 04-April 09

Posted 21 August 2009 - 03:44 AM

View Posttuyen, on 10 Aug, 2009 - 09:22 PM, said:

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 :) !

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.
Was This Post Helpful? 0
  • +
  • -

#9 binary_refinary  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 07-November 09

Posted 07 November 2009 - 02:45 AM

Hey,

many thanks for the quick tutorial !

hands down- the best tutor i've found on the net for c# text highlighting :)
Was This Post Helpful? 0
  • +
  • -

#10 Guest_Tanner*


Reputation:

Posted 25 March 2010 - 08:52 AM

Thanks a ton this is by far the easiest tutorial Ive seen on this :genius: , but one thing, I changed it to highlight HTML and when I enter a keyword it turns blue but if I erase half of it then start typing again all my text is turned blue when I type do you know what the problem is?
Was This Post Helpful? 0

#11 Guest_Guest*


Reputation:

Posted 11 April 2010 - 08:21 PM

Hello just want to tell people how to fix the bug I posted above, just change the line: <pre>richTextBox1.Selectionstart = selPos;</pre> to this: <pre>richTextBox1.Select(selectionstart, 0);</pre> and all the bugs are gone. :bigsmile:
Was This Post Helpful? 0

#12 Guest_Jamie*


Reputation:

Posted 24 June 2010 - 02:09 AM

To stop "break" being highlighted in "breakfast" etc a few changes need to be made:

public Regex keyWords = new Regex(@"\b(keyword1|keyword2|keyword3)\b");



               
 // get cursor position
                int selPos = tb_script.Selectionstart;

                // reset all text so we dont highlight the break in breakfast etc.
                tb_script.SelectAll();
                tb_script.SelectionColor = Color.Black;
                tb_script.Selectionstart = selPos;

                // highlight reserved words
                foreach (Match keyWordMatch in keyWords.Matches(tb_script.Text))
                {
                    tb_script.Select(keyWordMatch.Index, keyWordMatch.Length);
                    tb_script.SelectionColor = Color.Blue;
                    tb_script.Selectionstart = selPos;
                    tb_script.SelectionColor = Color.Black;
                }


Was This Post Helpful? 0

#13 aaron1178  Icon User is offline

  • Dovakiin, Dragonborn
  • member icon

Reputation: 169
  • View blog
  • Posts: 1,297
  • Joined: 22-October 08

Posted 15 November 2010 - 02:06 PM

I know this is old but Thanks this is just what i needed thanks u saved my life :)
Thanks Aaron1178
Was This Post Helpful? 0
  • +
  • -

#14 TheWinnieston  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 05-September 11

Posted 05 September 2011 - 11:38 AM

Where exactly do you insert the
[DllImport("user32.dll")] // import lockwindow to remove flashing
public static extern bool LockWindowUpdate (IntPtr hWndLock);

code? At the beginning of the Form? Right before the keywords? Where?

View Postgabehabe, on 24 September 2008 - 03:39 PM, said:

Nice tutorial! I just wish I could've found it before I wrote 500 lines of a class to do it -_-
Then again, my class deals with comments and block comments, too :)

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

Why not block that out with LockWindowUpdate() ?

[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:
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)

:)

Was This Post Helpful? 0
  • +
  • -

#15 blogwhodle  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 49
  • Joined: 18-January 12

Posted 18 January 2012 - 05:58 PM

View PostTheWinnieston, on 05 September 2011 - 11:38 AM, said:

Where exactly do you insert the
[DllImport("user32.dll")] // import lockwindow to remove flashing
public static extern bool LockWindowUpdate (IntPtr hWndLock);

code? At the beginning of the Form? Right before the keywords? Where?

View Postgabehabe, on 24 September 2008 - 03:39 PM, said:

Nice tutorial! I just wish I could've found it before I wrote 500 lines of a class to do it -_-
Then again, my class deals with comments and block comments, too :)

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

Why not block that out with LockWindowUpdate() ?

[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:
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)

:)

Umm... I am just a little kid who knows how to program. Basically you put that right before all the methods and stuff like that. For example
[...]
[DllImport("user32.dll")] // import lockwindow to remove flashing
public static extern bool LockWindowUpdate (IntPtr hWndLock);
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);}
}


:smile2:

View Postblogwhodle, on 18 January 2012 - 05:55 PM, said:

View PostTheWinnieston, on 05 September 2011 - 11:38 AM, said:

Where exactly do you insert the
[DllImport("user32.dll")] // import lockwindow to remove flashing
public static extern bool LockWindowUpdate (IntPtr hWndLock);

code? At the beginning of the Form? Right before the keywords? Where?

View Postgabehabe, on 24 September 2008 - 03:39 PM, said:

Nice tutorial! I just wish I could've found it before I wrote 500 lines of a class to do it -_-
Then again, my class deals with comments and block comments, too :)

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

Why not block that out with LockWindowUpdate() ?

[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:
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)

:)

Umm... I am just a little kid who knows how to program. Basically you put that right before all the methods and stuff like that. For example
[...]
[DllImport("user32.dll")] // import lockwindow to remove flashing
public static extern bool LockWindowUpdate (IntPtr hWndLock);
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);}
}


:smile2:

And Remember you must have
using System.Runtime.InteropServices;


For it to work
:smile2:
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2