[Latest News][6]

color C# keyword in RichTextBox
Highlight C# keyword in RichTextBox
How to Merge DataGridView Columns
How to Merge DataGridView Rows
How to Merge GridView Columns
How to Merge GridView Rows
how to send sms
Make SMS Gateway using C#.net
Merge DataGridView Columns
Merge DataGridView Rows
Merge GridView Columns
Merge GridView Rows
read sms
Send and Read SMS through a GSM Modem using AT Commands
send or read sms
sent sms
Syntax Highlighting in RichTextBox using C#

Syntax highlighting in RichTextBox using C#

Syntax highlighting in RichTextBox using C#

When we make an application like programming editor for language it provides syntax highlighting that makes the user comfortable to work with it as everybody likes colored text that can be easy to read and distinguish between normal variable names and language keywords.

In this code I will show you how provide such syntax highlighting feature in RichTextBox control.
Drag a RichTextBox control on the form.. Now we need when user types text it should be highlighted if its keyword of language. I will use Blue color here to highlight the keyword of language.

Now to make this feature available to user we need a collection of all keywords of language. So here in demonstration, I’m making syntax highlighting for C language so I need C language Keyword list…

I acquired all from here

http://msdn.microsoft.com/en-us/library/befeaky0.aspx

Now think about how we should update the color of text obviously it would be nice if we update color of text to blue as we type in RichTextBox. So we will write code in RichTextBox’s text changed event.

private void richTextBox1_TextChanged(object sender, EventArgs e)
{
    string tokens = "(auto|double|int|struct|break|else|long|switch|case|
                     enum|register|typedef|char|extern|return|union|const|
                     float|short|unsigned|continue|for|signed|void|default|
                     goto|sizeof|volatile|do|if|static|while)";
    Regex rex = new Regex(tokens);
    MatchCollection mc = rex.Matches(richTextBox1.Text);
    int StartCursorPosition = richTextBox1.SelectionStart;
    foreach (Match m in mc)
    {
        int startIndex = m.Index;
        int StopIndex = m.Length;
        richTextBox1.Select(startIndex, StopIndex);
        richTextBox1.SelectionColor = Color.Blue;
        richTextBox1.SelectionStart = StartCursorPosition;
        richTextBox1.SelectionColor = Color.Black;
    }
}
 
You can see here in first line I have written all the keywords of C 
language that we want to highlight. Then I match collection and color 
them one by one by selecting it and change its font color. And here is 
my result.
 
 
 

About Author Mohamed Abu 'l-Gharaniq

when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries.

No comments:

Post a Comment

Start typing and press Enter to search