Search

Syntax highlight using RichTextBox

This example uses the RegEx to search the keywords and highlight them with different color

//Synatx Highlight inside Rich Text box
private void HighLightSyntax()
{
//rtbCommand.Enabled = false;
//rtbCommand.ReadOnly = true;
//rtbCommand.Cursor = Cursors.No;
rtbCommand.BorderStyle = BorderStyle.None;
//Add RichTextBox
// private System.Windows.Forms.RichTextBox rtbCommand;
//define the JScript keywords
string jSkeywords = "abstract|arguments|boolean|break|byte";
jSkeywords = jSkeywords.Replace("|", "\\b|\\b");
// create regular Expression
Regex regExp = new Regex( "\\b" +jSkeywords + "\\b",
RegexOptions.Compiled | RegexOptions.Multiline);
//find all the matches in match collection
MatchCollection _matches = regExp.Matches(rtbCommand.Text);
// process all the matched keywords
foreach (Match match in _matches)
{
rtbCommand.Select(match.Index, match.Length);
rtbCommand.SelectionColor = Color.Red;
//de-select word and move cursor to the end
rtbCommand.DeselectAll();
rtbCommand.SelectionStart = rtbCommand.Text.Length;
}
}
/*It can be called onKeyUp event like
if(e.KeyCode == Keys.Enter)
{
HighLightSyntax();
}*/