andypaxo
andypaxo

Reputation: 6621

RichTextBox SelectionFont is unexpectedly *not* null

I'd like to change the font size of a chunk of RTF without erasing the bold / italic / underline formatting (an issue similar to the one in this question). The accepted answer is to modify the selection of the text box until the SelectionFont propery is null in order to find runs of consistently formatted text which can be modified individually. Sounds reasonable. However the actual behavior of the RichTextBox control seems to be inconsistent with the documentation.

In the documentation for RichTextBox.SelectionFont MSDN states:

If the current text selection has more than one font specified, this property is null.

However, this code which uses mixed bold / regular text doesn't behave as you'd expect:

var rtb = new RichTextBox {
    Rtf = @"{\rtf1 This is \b bold\b0.}"
};

rtb.SelectAll();
// Now you'd expect rtb.SelectionFont to be null,
// but it actually returns a Font object

Is there any other reliable way of formatting the text so that I can change the font size without clobbering the other formatting. (Manipulating the RTF directly is OK, I'm not absolutely set on using WinForms to achieve this).

Upvotes: 0

Views: 1022

Answers (2)

Jerry
Jerry

Reputation: 4408

Take a look at this: Changing font for richtextbox without losing formatting

I think it's the same issue. LarsTech's solution is working perfectly for me.

Upvotes: 0

andypaxo
andypaxo

Reputation: 6621

I've given up on trying to go through Winforms to fix this. As I'm applying the change to a whole document (rather than just one portion), it turns out that it's not too hard to modify the RTF directly.

In this case I'm interested in the font size, which is represented by the \fs command. So to replace all the 8.5pt text with 10pt text, you can replace \fs17 with \fs20. (Yes, RTF font sizes come in units of half a point, apparently).

This seems to work well enough, although it does feel like one of those "let's mangle our HTML using regular expressions" type solutions, so I'm not convinced that it's very robust.

Upvotes: 0

Related Questions