Visual Basic richtextbox - setting specific text to Italic font style

后端 未结 3 1974
庸人自扰
庸人自扰 2021-01-25 09:56

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 =         


        
3条回答
  •  一向
    一向 (楼主)
    2021-01-25 10:52

    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
    

    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).

提交回复
热议问题