大家好,并提前致谢,
我有一个文本框,其中正在生成一些文本。在生成它的同时,我想用“绿色”和“失败”这个词为“成功”这个词加上颜色。
我正在使用它:
FormtxtBox.Find()("successfully")
FormtxtBox.SelectionColor = Color.YellowGreen
FormtxtBox.SelectionFont = New Font(FormtxtBox.Font.FontFamily, FormtxtBox.Font.Size, FontStyle.Bold)
FormtxtBox.DeselectAll()
FormtxtBox.Find("failed")
FormtxtBox.SelectionColor = Color.Red
FormtxtBox.SelectionFont = New Font(FormtxtBox.Font.FontFamily, FormtxtBox.Font.Size, FontStyle.Bold)
FormtxtBox.DeselectAll()
它正在工作,但我遇到的问题是它只会着色第一个“成功”或“失败”字符串,而文本框中有该字的许多副本。我怎样才能为这些单词的每一个副本着色?
答案 0 :(得分:1)
是的,吉尔说,发现只发现了第一次出现。
https://msdn.microsoft.com/en-us/library/hfcsf75k(v=vs.110).aspx
我确实找到了这篇文章并稍作修改:
https://support.microsoft.com/en-us/kb/176643
它递归搜索RichTextBox,选择搜索的文本,并按指定更改文本。如果您正在更改字体,则需要为字体添加其他参数。
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
FindIt(Me.RichTextBox1, "failed", Color.Red)
End Sub
Private Function FindIt(ByRef Box As RichTextBox, ByVal Search As String, ByVal Color As Color, Optional Start As Int32 = 0) As Int32
Dim retval As Int32 'Instr returns a long
Dim Source As String 'variable used in Instr
Try
Source = Box.Text 'put the text to search into the variable
retval = Source.IndexOf(Search, Start) 'do the first search,
'starting at the beginning
'of the text
If retval <> -1 Then 'there is at least one more occurrence of
'the string
'the RichTextBox doesn't support multiple active selections, so
'this section marks the occurrences of the search string by
'making them Bold and Red
With Box
.SelectionStart = retval
.SelectionLength = Search.Length
.SelectionColor = Color
.DeselectAll() 'this line removes the selection highlight
End With
Start = retval + Search.Length 'move the starting point past the
'first occurrence
'FindIt calls itself with new arguments
'this is what makes it Recursive
FindIt = 1 + FindIt(Box, Search, Color, Start)
End If
Catch ex As Exception
Debug.WriteLine(ex.Message)
End Try
Return retval
End Function