I am making Richtextbox Editor with Regex to format few specific words. I am using below code:
private void myrichTextBox1_TextChanged(object sender, EventArgs e)
{
// getting keywords/functions
string keywords = @"\b(public|private|sendln|static|namespace|Wait|using|void|foreach|in|OK|ERROR)\b";
MatchCollection keywordMatches = Regex.Matches(richTextBox1.Text, keywords);
// getting types/classes from the text
string types = @"\b(Console)\b";
MatchCollection typeMatches = Regex.Matches(richTextBox1.Text, types);
// getting comments (inline or multiline)
string comments = @"(\/\/.+?$|\/\*.+?\*\/)";
MatchCollection commentMatches = Regex.Matches(richTextBox1.Text, comments, RegexOptions.Multiline);
// getting strings
string strings = "\".+?\"";
MatchCollection stringMatches = Regex.Matches(richTextBox1.Text, strings);
// saving the original caret position + forecolor
int originalIndex = richTextBox1.SelectionStart;
int originalLength = richTextBox1.SelectionLength;
Color originalColor = Color.Black;
// MANDATORY - focuses a label before highlighting (avoids blinking)
titleLabel.Focus();
// removes any previous highlighting (so modified words won't remain highlighted)
richTextBox1.SelectionStart = 0;
richTextBox1.SelectionLength = richTextBox1.Text.Length;
richTextBox1.SelectionColor = originalColor;
// scanning...
foreach (Match m in keywordMatches)
{
richTextBox1.SelectionStart = m.Index;
richTextBox1.SelectionLength = m.Length;
richTextBox1.SelectionColor = Color.Blue;
}
foreach (Match m in typeMatches)
{
richTextBox1.SelectionStart = m.Index;
richTextBox1.SelectionLength = m.Length;
richTextBox1.SelectionColor = Color.DarkCyan;
}
foreach (Match m in commentMatches)
{
richTextBox1.SelectionStart = m.Index;
richTextBox1.SelectionLength = m.Length;
richTextBox1.SelectionColor = Color.Green;
}
foreach (Match m in stringMatches)
{
richTextBox1.SelectionStart = m.Index;
richTextBox1.SelectionLength = m.Length;
richTextBox1.SelectionColor = Color.Brown;
}
// restoring the original colors, for further writing
richTextBox1.SelectionStart = originalIndex;
richTextBox1.SelectionLength = originalLength;
richTextBox1.SelectionColor = originalColor;
// giving back the focus
richTextBox1.Focus();
}
Since there was continous flickering on text edit, hence moved the focus to label titleLabel.Focus();
.
But on launch, its giving below exception:
An unhandled exception of type 'System.StackOverflowException' occurred in System.Windows.Forms.dll.
Without titleLabel.Focus();
there is no Exception but Continous Blinking.