【发布时间】:2012-01-24 14:30:12
【问题描述】:
我需要像在 notepad.exe 中一样向用户显示光标上文本的选择开始和长度。
选择长度没有问题,因为 Richtextbox 支持带有开始和结束的选择属性。
但如果我将光标设置在文档的第一个位置,我的 RichTexbox 的 startindex 始终是 2 而不是 0。
如果我清除完整的文本,它位于0。但是如果我按SPACE 然后BACKSPACE 文本框是空的,但StartIndex 的计数器在2
有什么想法吗?
* 编辑 * 第一个解决方案
好的,这是我的一个可行的解决方案。但我认为有更好的方法。
''' <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
【问题讨论】:
-
RichTextBox 自动创建一个段落和一个运行(或类似的东西),因此非零索引。光标不在开头,而是在第一段的第一次运行。
-
再次感谢 H.B.为了您的快速响应。你有什么解决办法吗?
-
不,否则我会发布答案。
-
尝试在
TextPointer类对象上使用GetPointerContext方法来验证它的值是否为TextPointerContext.Text。您还可以在此处找到有关RichTextBox选择的更多信息:stackoverflow.com/questions/1454440/…。它是关于选择文本而不是检查选择,但它可能对您有所帮助(如果您想获取文本选择的开始和结束位置)。如果您想了解更多信息,请向我们提供有关您希望这部分代码做什么的更多详细信息。 -
感谢卢卡斯的回答。搜索字符的方式不是很好,但很有效。我对我的解决方案不满意(在上面),我会等待。也许有人知道如何使用 RTB 内部实现。
标签: .net wpf text richtextbox