我有一个带有 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 上突出显示的所选文本并将鼠标光标保留在用户单击的位置。
非常感谢任何人可以提供的帮助。
最佳答案
我认为你可能想得太多了。
在右键事件中,尝试RtbMain.SelectionLength = 0
关于vb.net - 在不滚动的情况下删除 RichTextBox 中先前选择的突出显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40420166/