4
votes

How do I change only the font family in a RichTextBox (RTB) keeping the font size unchanged? I have a RTB that could have text in different font and font size, I would like to change all the content to have a new Font family but retain whatever size they have from the user. How could I achieve this? I am aware of a SelectionFont property, but every overload of Font constructor requires the font size as well.

        RichTextBox rtb = new RichTextBox();
        // some code that adds various text of different fonts and font sizes
        rtb.SelectAll();
        rtb.SelectionFont = new Font("arial", ??);

Also I did come across Lars Tech’s solution on this SO post, but I think that is too complicated and too much work to achieve the feature.

1
It looks like Lars' solution may be the way to go if you have multiple styles in the same RichTextBox. Other solutions I have seen are able to maintain font size/etc. only if all the text in the RichTextBox uses the same style (font, bold, size, etc.)dub stylee

1 Answers

3
votes

If you want to avoid the pinvoking solution, then you would have to loop through the characters individually. To avoid flicker, you can use an offscreen RichTextBox control to apply the changes:

using (RichTextBox tmpRB = new RichTextBox()) {
  tmpRB.SelectAll();
  tmpRB.SelectedRtf = rtb.SelectedRtf;
  for (int i = 0; i < tmpRB.TextLength; ++i) {
    tmpRB.Select(i, 1);
    tmpRB.SelectionFont = new Font("Arial", tmpRB.SelectionFont.Size);
  }
  tmpRB.SelectAll();
  rtb.SelectedRtf = tmpRB.SelectedRtf;
}