haku
haku

Reputation: 4505

Change RichTextBox font family only not FontSize

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.

Upvotes: 4

Views: 2612

Answers (1)

LarsTech
LarsTech

Reputation: 81610

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;
}

Upvotes: 3

Related Questions