首页 文章

删除以前在RichTextBox中突出显示的选项而不滚动

提问于
浏览
3

我有一个包含RichTextBox(RTB)和listBox的表单 .

当最终用户选择列表框中的项目时,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

我需要我的代码来模拟标准窗口行为 - 清除MouseDown上选定的文本突出显示并将鼠标光标留在用户单击的位置 .

感谢任何人提供的任何帮助 .

1 回答

  • 0

    我想你可能会过度思考这个问题 .

    在右键单击事件中,尝试RtbMain.SelectionLength = 0

相关问题