Visual Basic richtextbox - setting specific text to Italic font style

空扰寡人 提交于 2019-12-02 06:56:00

问题


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.

Hello my name is Bob.

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

Cheers!


回答1:


Try this:

Me.RichTextBox1.Rtf = "{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fnil\fcharset0 Calibri;}} hello my name is \i Bob\i0 \par}"

If you use wordpad to write some sample text, save it in rtf format and then open the file in notepad, you will get something to start with. You can remove some of what wordpad adds (like the program that generated it) but it looks like you have to leave in at least the code page and at least one font.




回答2:


Dim BO As New Font("Arial", 12, FontStyle.italic) ' Italic
  richtextbox1.text = "Hello my name is " 
  richtextbox1.selectionfont = BO
  richtextbox1.appendtext(name)

Hope this helps




回答3:


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



来源:https://stackoverflow.com/questions/5362957/visual-basic-richtextbox-setting-specific-text-to-italic-font-style

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!