Using the Selection property does not work well. It changes what is currently selected on the screen. I have attempted to reset the selection on the screen back to its original state, but this has caused other issues. Seems very odd that I can't simply get the text up to a certain point within the document, or even between points.
My issue is that I need to know what is BEFORE the cursor at all times. So, I run the following code on all mouse left button up events and all key up events:
// save the current cursor position and any highlighted text
Point cursorPosition = ctl.Document.CaretPosition.Location.ToPoint();
var selectedStartPosition = ctl.Document.Selection.Ranges.First;
var selectedLastPosition = ctl.Document.Selection.Ranges.Last;
DocumentPosition startPosition = ctl.Document.CaretPosition;
DocumentPosition endPosition = new DocumentPosition(startPosition);
// save the text position where a new statement would be inserted
CurrentlySelectedPFText = ctl.Document.Selection.GetSelectedText();
// clear the text that was selected
// reselect any selected text
if (selectedStartPosition != null || selectedLastPosition != null)
// reset the cursor position
This works somewhat correctly but I find the cursor tends to move up one line when you are just typing something into the control. Any ideas how I can better get all text BEFORE the cursor or a better way to implement this would be greatly appreciated.