如何格式化 RichTextBox 括号内的文本?
How to Format text within bracket for RichTextBox?
我有这样一个字符串:[1]新年快乐[2]生日快乐[3]一起快乐
我想将数字 1、2、3 格式化为红色。所以我把字符串放到 RichTextBox 中,然后像下面的代码一样进行搜索和格式化:
(我所做的是,找到“[”和“]”并保存到一个全局变量(i,j),然后每次我得到一组新的 i,j 时都会触发格式化事件。但是,它不会做我预期。: (
Public i, j As Integer
Dim s As String = "[1] Happy New year [2] Happy Birthday [3] Happy Together"
'Button Code
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim count As Integer = 0
rtfbuffer.Text = s
rtfbuffer.Font = New Font("Tahoma", 12, FontStyle.Bold)
rtfbuffer.ForeColor = Color.Black
Do While count < s.Length - 1
If s.Chars(count) = "[" Then
i = count
count += 1
ElseIf s.Chars(count) = "]" Then
j = count + 1
count += 1
rtfbuffer.Select(i, j)
rtfbuffer.SelectionColor = Color.Red
Else
count += 1
End If
Loop
最后,我只能得到“[]”红色内的第一个文本。看代码,我不明白为什么它没有经过剩余的文本。你能告诉我如何纠正它吗?
非常感谢~
Select
方法的第二个参数是 select 的文本长度。参见 MSDN。
Public 子 Select (
以整数开始,
长度为整数
)
Parameters
start Type: System.Int32 The position of the first character in the current text selection within the text box.
length Type: System.Int32 The number of characters to select.
因此,在您的代码中,当您调用 Select
时,您可以通过提供 j - i
而不是仅 j
来计算 select 的长度(然后突出显示) .它第一次在您的代码中起作用,因为 'end index' (j
) 实际上与长度相同,即 3.
rtfbuffer.Select(i, j - i)
rtfbuffer.SelectionColor = Color.Red
我有这样一个字符串:[1]新年快乐[2]生日快乐[3]一起快乐 我想将数字 1、2、3 格式化为红色。所以我把字符串放到 RichTextBox 中,然后像下面的代码一样进行搜索和格式化: (我所做的是,找到“[”和“]”并保存到一个全局变量(i,j),然后每次我得到一组新的 i,j 时都会触发格式化事件。但是,它不会做我预期。: (
Public i, j As Integer
Dim s As String = "[1] Happy New year [2] Happy Birthday [3] Happy Together"
'Button Code
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim count As Integer = 0
rtfbuffer.Text = s
rtfbuffer.Font = New Font("Tahoma", 12, FontStyle.Bold)
rtfbuffer.ForeColor = Color.Black
Do While count < s.Length - 1
If s.Chars(count) = "[" Then
i = count
count += 1
ElseIf s.Chars(count) = "]" Then
j = count + 1
count += 1
rtfbuffer.Select(i, j)
rtfbuffer.SelectionColor = Color.Red
Else
count += 1
End If
Loop
最后,我只能得到“[]”红色内的第一个文本。看代码,我不明白为什么它没有经过剩余的文本。你能告诉我如何纠正它吗? 非常感谢~
Select
方法的第二个参数是 select 的文本长度。参见 MSDN。
Public 子 Select ( 以整数开始, 长度为整数 )
Parameters
start Type: System.Int32 The position of the first character in the current text selection within the text box.
length Type: System.Int32 The number of characters to select.
因此,在您的代码中,当您调用 Select
时,您可以通过提供 j - i
而不是仅 j
来计算 select 的长度(然后突出显示) .它第一次在您的代码中起作用,因为 'end index' (j
) 实际上与长度相同,即 3.
rtfbuffer.Select(i, j - i)
rtfbuffer.SelectionColor = Color.Red