【发布时间】:2017-04-05 06:13:39
【问题描述】:
我正在编写一个代码来突出显示文本中的重复单词。当我添加一个按钮并且用户必须按下按钮来检查重复项时,代码运行良好。
但我想制作一个自动检查代码。我将代码设置在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
【问题讨论】:
-
为什么必须保持选中副本?如果有多个重复项怎么办?只需突出显示文本,让他们继续打字而不会干扰。
-
@AFriend 高亮后如何取消选中文本?
标签: vb.net richtextbox