【发布时间】:2017-03-18 03:20:54
【问题描述】:
我有一个带有 RichTextBox (RTB) 和一个列表框的表单。
当最终用户选择列表框中的项目时,RTB 中的所有匹配文本都会突出显示(为简洁起见,删除了完整代码)。
re = New Regex(txtToFind)
For Each m In re.Matches(rtbMain.Text)
rtbMain.[Select](m.Index, m.Length)
rtbMain.SelectionColor = Color.White
rtbMain.SelectionBackColor = System.Drawing.SystemColors.Highlight
Next
当用户在 RTB 中单击鼠标左键时,我希望清除之前突出显示的文本。这是标准的 Windows 行为 - 如果您使用鼠标手动选择 RTB 中的某些文本,它会突出显示,单击 RTB 中的任意位置,突出显示就会消失。我以编程方式选择的文本保持选中状态。
我有一些部分工作的代码(如下)。我可以清除所有突出显示的文本,但这是通过选择所有内容、更改颜色然后再次取消选择的过程。我知道它效率不高,RTB 闪烁,我确信这不是正确的方法。我可以模拟标准的 Windows 行为吗?
同样使用我的代码,第二次进入 RTB 时它会滚动到第一行。
我第一次通过在清除文本之前返回顶部可见行索引然后再次选择该行并使用 ScrollToCaret() 来解决这个问题。这仅适用于第一遍。后续的 MouseDown 事件会选择顶行,而不管用户在何处单击,因此无法在 RTB 中手动突出显示任何内容。
Private Sub rtbMain_MouseDown(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles rtbMain.MouseDown
Dim topIndex As Integer = rtbMain.GetCharIndexFromPosition(New System.Drawing.Point(1, 1))
Dim topLine As Integer = rtbMain.GetLineFromCharIndex(topIndex)
If e.Button = Windows.Forms.MouseButtons.Right Then
'Do nothing (Context Menu)
Else
rtbMain.SelectAll()
rtbMain.SelectionColor = Color.Black
rtbMain.SelectionBackColor = Color.White
rtbMain.DeselectAll()
rtbMain.Select(topIndex, 0)
rtbMain.ScrollToCaret()
End If
End Sub
我需要我的代码来模拟标准的 Windows 行为 - 清除 MouseDown 上突出显示的选定文本并将鼠标光标留在用户单击的位置。
感谢任何人提供的任何帮助。
【问题讨论】:
标签: vb.net richtextbox highlight