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

时间:2017-04-05 06:13:40

标签: vb.net richtextbox

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

但我想制作一个自动检查代码。我在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

1 个答案:

答案 0 :(得分:1)

在您的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