Retrieving font name of selected text in RichTextBox

613 Views Asked by At

I'm trying to retrieve font names for each line of text in a RichTextBox (each line is having a different font). Below is the code that I'm using to get the font name of second line in the RTB.

RichTextBox2.Select(RichTextBox2.Lines(0).Length + 1, 
                    RichTextBox2.Lines(1).Length)
font = RichTextBox2.SelectionFont.Name

But I'm getting the font name of the first line of textbox. Any help is appreciated.

1

There are 1 best solutions below

2
On BEST ANSWER

Try using the GetFirstCharIndexFromLine function to get the beginning point of each line:

For i As Integer = 0 To RichTextBox2.Lines.Count - 1
  RichTextBox2.Select(RichTextBox2.GetFirstCharIndexFromLine(i),
                      RichTextBox2.Lines(i).Length)
  MessageBox.Show(RichTextBox2.SelectionFont.Name)
Next

This is what I used to setup the RichTextBox control:

RichTextBox2.Clear()
RichTextBox2.SelectionFont = New Font("Segoe UI", 16)
RichTextBox2.AppendText("This is the First Line" & Environment.NewLine)
RichTextBox2.SelectionFont = New Font("Calibri", 12)
RichTextBox2.AppendText("This is the Second Line" & Environment.NewLine)
RichTextBox2.SelectionFont = New Font("Arial", 16)
RichTextBox2.AppendText("This is the Third Line" & Environment.NewLine)