Check you code out, you'll have problem if you start editing from INSIDE. You change your SelectionStart without deselecting anything.. this mean that selection changes instead of only having your cursor moving.
foreach(Match m in mc)
{
int startIndex = m.Index;
txtCode.Select(startIndex, m.Length);
txtCode.SelectionColor = Color.Blue;
txtCode.DeselectAll();
txtCode.SelectionStart = StartCursorPosition;
txtCode.SelectionColor = Color.Black;
}
There will still be flickering too and keywords in strings will still be marked in blue. One trick would be to check for strings AFTER checking for keywords.
tokens = "\\\".*\\\"";
rex = new Regex(tokens);
mc = rex.Matches(txtCode.Text);
StartCursorPosition = txtCode.SelectionStart;
foreach(Match m in mc)
{
int startIndex = m.Index;
txtCode.Select(startIndex, m.Length);
txtCode.SelectionColor = Color.Brown;
txtCode.DeselectAll();
txtCode.SelectionStart = StartCursorPosition;
txtCode.SelectionColor = Color.Black;
}
You still have problems with backspaces because formatting is kept even if you remove text. One trick is to remove all formatting and redo everything.
private void ResetFormatting()
{
int StartCursorPosition = txtCode.SelectionStart;
string s = txtCode.Text;
txtCode.ResetText();
txtCode.Text = s;
txtCode.SelectionStart = StartCursorPosition;
UpdateFormatting();
}
If you want to reduce flickering, you could only update in special occasions like when you press Space. It's still a really slow way of doing things. If you want to have a great syntax highlighter, I think you need more intelligence. If you understand what the person is writing, it helps a lot updating smartly and not restart all formatting. For example, you could update only one instruction instead of doing all the text.
Working with selections is not the best either. I think this is a major cause of flickering. You could use a model for your code that contains everything including the syntax changes. Instead of selecting text and changing format every time text changes, it could be written directly with the good syntax.
If you only SHOW code and do not allow editing, one time format updating might be enough. Test it out.
Please not that I don't suppose that my code work. It's still completely unsuitable for code-highlight. It will even detect keywords inside other words.
"Therefore" for example will have the "for" in blue. There's tons of flaws, however it is still a good way to start everything. Good luck.