You can use TextView.GetPosition
to retrieve the document position for the corners of the text view:
TextViewPosition? start = textView.GetPosition(new Point(0, 0) + textView.ScrollOffset);
TextViewPosition? end = textView.GetPosition(new Point(textView.ActualWidth, textView.ActualHeight) + textView.ScrollOffset);
You can use TextDocument.GetOffset
to convert a TextViewPosition into an offset. Note that you can get back null
when there is no line at the specified point - within the visible area, that should occur only if the end of the visible area is behind the end of the document, so you should be able to assume the end of the document in those cases:
int startOffset = start != null ? document.GetOffset(start.Value) : document.TextLength;
int endOffset = end != null ? document.GetOffset(end.Value) : document.TextLength;
However, if you want to, you can also work directly with the VisualLine/TextLines: VisualLine.VisualTop
tells you where a visual line starts (Y coordinate), and every TextLine within the VisualLine has a Height
property. Using these, you can determine which text lines are visible, then use their GetCharacterHitFromDistance
method to retrieve a visual column, and use VisualLine.GetRelativeOffset
to calculate the text offset from the visual column. (this is what the TextView.GetPosition
method is doing)