Reputation: 355
I am trying to use Regex
to highlight numbers in my RichTextBox
RTB, and it works fine, except when I press move the caret position to above where I was, it selects the stuff below, and when I type, it dissapears, unless I am constantly pressing the left key, which is a real nuisance.
Code:
MyRegex.cs
namespace REGEX_MY
{
public class REGEX_CLASS
{
public static RichTextBox HIGHLIGHT(RichTextBox RTB, int StartPos)
{
Regex Red = new Regex("1|2|3|4|5|6|7|8|9|0");
RTB.SelectAll();
RTB.SelectionColor = Color.White;
RTB.Select(RTB.Text.Length, 1);
foreach (Match Match in Red.Matches(RTB.Text))
{
RTB.Select(Match.Index, Match.Length);
RTB.SelectionColor = Color.Blue;
RTB.SelectionStart = StartPos;
RTB.SelectionColor = Color.White;
}
return RTB;
}
}
}
MyForm.cs
public void DoIt()
{
RTB = REGEX_MY.REGEX_CLASS.HIGHLIGHT(RTB, RTB.SelectionStart);
}
Thanks :)
Upvotes: 1
Views: 333
Reputation: 1736
RTB.Select(Match.Index, Match.Length)
in foreach
statement is jumping a 1 length selection over the matched digits. When it finishes, it keeps the selection over the last matched digit, and when you press any key the selection does not disappear but the cursor moves forward, so the next character gets overwritten.
The solution is to bring back the cursor to the starting position without selection range just after the foreach
statement gets finished, like this RTB.Select(StartPos, 0)
foreach (Match Match in Red.Matches(RTB.Text))
{
RTB.Select(Match.Index, Match.Length);
RTB.SelectionColor = Color.Blue;
RTB.SelectionStart = StartPos;
RTB.SelectionColor = Color.White;
}
RTB.Select(StartPos, 0);
return RTB;
Upvotes: 2