Reputation: 4900
I need to show the user, like in notepad.exe, the selection start and length of his text on cursor.
Selection length is no problem because Richtextbox supports the Selection Property with Start and End.
But the startindex of my RichTexbox is always 2
instead of 0
if I set the cursor on first position of the document.
If I CLEAR the complete text it is on 0
. But if I press SPACE
and then BACKSPACE
the textbox is empty but the counter of StartIndex is on 2
Any idea?
* EDIT * FIRST SOLUTION
Ok, thats a working solution of mine. But I think there is a better way to do it.
''' <summary>
''' Get the position of the cursor. Ignores all formatting characters like ENTER and PARAGRAPH. Just counts the visible characters.
''' </summary>
''' <param name="rtb">The richtextbox the value should be determined</param>
''' <returns>Index value of the cursor. 0 is at the first position. After position is behind characters "123" it would return the index 3.</returns>
''' <remarks>Watch out for performance, Use this methode in separated. Timo Böhme, 2012</remarks>
Private Function GetPositionOfCursor(ByVal rtb As RichTextBox) As Integer
Dim contentStart As TextPointer = rtb.Document.ContentStart
Dim res As Integer = 0
Dim CursorIndex As Integer = contentStart.GetOffsetToPosition(rtb.CaretPosition)
Dim j As Integer = 0
Do
If j > CursorIndex Then Exit Do
If contentStart.GetPositionAtOffset(1, LogicalDirection.Forward) Is Nothing Then
Exit Do
ElseIf contentStart.GetPointerContext(LogicalDirection.Backward) = TextPointerContext.Text Then
res += 1
End If
contentStart = contentStart.GetPositionAtOffset(1, LogicalDirection.Forward)
j += 1
Loop
Return res
End Function
Upvotes: 4
Views: 2661
Reputation: 35
I do not know whether this is a real answer to your question, but I use this simple trick to retrieve the cursor index related tot the text:
TextRange range = new TextRange(Document.ContentStart, CaretPosition);
int n = range.Text.Length;
I'm working on an editor based on the WPF richtextbox. Since real time formatting (like highlighting keywords and such) is really slow I create a new document in another thread. In this thread the text gets formatted in appropiate runs, rather than formatting them as a part of the richtextbox's paragraph. Once finished the original one is replaced by the new one. Works really nice and incredible fast (compared to the MS way at least).
I hope this give you some inspiration and/or ideas.
Upvotes: 3