Visual Basic Richtextbox - 将特定文本设置为斜体字体样式

问题描述:

我创建了一个 Richtextbox,它根据用户输入的变量以及一些基本格式生成文本 - 例如:

I have created a Richtextbox, which produces text based on user-inputted variables as well as some basic formatting - eg:

name = txtname.text
richtextbox1.text = "Hello my name is " & name & "."

我想要做的是在显示时将名称变量中的文本设置为斜体,就像这样.

What i want to do is set the text in the name variable in Italics when it is displayed, like this.

你好,我叫鲍勃.

我能找到的最好的方法是选择范围,但没有运气.

Best I've been able to find is to do with selection ranges, but not had any luck with that.

干杯!

我写了一个小程序来做到这一点:

I wrote a little routine that does this:

Private Sub changeRTF(ByVal strToChange As String, ByRef richTextBox As RichTextBox, ByVal color As Color, Optional ByVal ital As Boolean = False, Optional ByVal bold As Boolean = False, Optional ByVal pointSize As Single = -1)
    richTextBox.SelectionStart = richTextBox.Find(strToChange, RichTextBoxFinds.MatchCase)

    If ital And bold Then
        richTextBox.SelectionFont = New Font(richTextBox.Font, FontStyle.Bold + FontStyle.Italic)
    Else
        If ital Then richTextBox.SelectionFont = New Font(richTextBox.Font, FontStyle.Italic)
        If bold Then richTextBox.SelectionFont = New Font(richTextBox.Font, FontStyle.Bold)
    End If

    richTextBox.SelectionColor = color

    Dim originalFontFamily As FontFamily = richTextBox.SelectionFont.FontFamily
    Dim originalFontStyle As FontStyle = richTextBox.SelectionFont.Style

    If pointSize > 0 Then richTextBox.SelectionFont = New Font(originalFontFamily, pointSize, originalFontStyle)
End Sub

因此,您将创建文本,然后调用 changeRTF("Bob",richtextbox1,color.gold,true).

So, you would create your text, and then call changeRTF("Bob",richtextbox1,color.gold,true).

这段代码的唯一问题是它目前只能找到您要查找的字符串的第一个存在.我用它来突出标题,所以到目前为止还没有问题(我不重复标题).

The only problem with this code is it currently only finds the first existence of the string you are looking for. I use it to highlight titles so it hasn't been a problem so far (I don't repeat the titles).