在用户键入时突出显示特定文本

Highlight specific text while user is typing

我正在编写一个代码来突出显示文本中的重复单词。当我添加一个按钮并且用户必须按下按钮以检查重复项时,代码运行良好。

但是我想做一个自动校验码。我将我的代码设置在 Handles RichTextBox.TextChanged 的子例程中。问题是代码选择了目标词并将其突出显示,但选择仍然存在,因此当键入新字母时,它会清除突出显示的内容。

这是我的代码:

Private Sub RichTextBox_TextChanged(sender As Object, e As EventArgs) Handles RichTextBox.TextChanged
        Try

        Call duplicate_check()

    Catch ex As Exception
        MessageBox.Show("error in RichTextBox.TextChanged")
    End Try
End Sub

重复检查功能:

Private Sub duplicate_check()
        Try
            ' read line by line and get input 
            Dim LineByLineInput() As String = RichTextBox.Lines
            Dim selectionStart, selectionLength As Integer
            Dim i, j As Integer

            For lineNumber = 0 To UBound(LineByLineInput)
                selectionStart = 0
                selectionLength = 0
                'get index of first char index in the current line
                Dim count As Integer = lineNumber
                While count <> 0
                    selectionStart += RichTextBox.Lines(count - 1).Length + 1
                    count -= 1
                End While
                ' get line as string
                Dim line As String = RichTextBox.Lines(lineNumber)
                ' split line into array of strings
                Dim input() As String = line.Split(" ")
                'check for duplicates
                i = 0
                For j = i + 1 To UBound(input)

                    If input(i) = input(j) Then 'compare each 2 consecutive words if they are the same
                        selectionStart += input(i).Length + 1
                        selectionLength = input(i).Length
                        RichTextBox.SelectionStart = selectionStart
                        RichTextBox.SelectionLength = selectionLength
                        RichTextBox.SelectionBackColor = Color.Yellow

                    Else
                        selectionStart += input(i).Length + 1
                    End If
                    i += 1
                Next
            Next
        Catch ex As Exception
            MessageBox.Show("error duplicate_check()")
        End Try

    End Sub

在您 duplicate_check 调用之后,您是否尝试将 RichTextBox 的选择设置回原来的位置?

见下文:

 Private Sub RichTextBox1_TextChanged(sender As Object, e As System.EventArgs) Handles RichTextBox1.TextChanged
        Try
            ' Get current position
            Dim cur_pos As Integer = Me.RichTextBox.SelectionStart
            Call duplicate_check()
            ' Set back to old position
            Me.RichTextBox.SelectionStart = cur_pos
            ' Unselect what your sub duplicate_check has selected
            Me.RichTextBox1.SelectionLength = 0

        Catch ex As Exception
            MessageBox.Show("error in RichTextBox.TextChanged")
        End Try
    End Sub

如果此解决方案适合您,您应该更改 duplicate_check Sub 来进行此更改,而不是在 RichTextBox1_TextChanged Sub