If I drag (back to front) to select text in a RichTextBox, the Selection.Text matches the actual selection.
However, If I drag (front to back) to select text in that same RichTextBox, the Selection.Text is always an empty string.
The reason I need this information, is that after re-parsing (this involves clearing all the text and repopulating it) the text in the RichTextBox, I need to return the caret to the original position.
My goal is to get the offset of the start of the selection. I can use that to get a string that stops there, which I will use to replace the caret at the end of the parsing.
if (String.IsNullOrWhiteSpace(Selection.Text))
restartPosition = activeRun.ContentStart.GetOffsetToPosition(CaretPosition.GetInsertionPosition(LogicalDirection.Forward));
else
restartPosition = activeRun.ContentStart.GetOffsetToPosition(Selection.Start);
The key is in that ‘if’ statement. If there is no selection, I can just use the text pointer for where the cursor is. If however there is a selection, I need the beginning of it. Ironically, if it were failing in the other direction it wouldn’t be an issue.
Is there a way to accurately retrieve the selection? Microsoft’s implementation seems a bit flawed.
So, it wasn’t broken. Changing the CaretPosition clears the selection. That was what was happening. Works like a champ now.