How to change the font of all the contents of a richtextbox without losing formatting?
I am trying to use
rtb.SelectAll();
rtb.SelectionFont = new Font(fontName,...);
but the font constructor has to take besides the font type either the font style (bold, italics, ...) or font size. So using this would change the style/size of all the content of the richtextbox.
Of course the same applies for any selection in the richtextbox.
This is a RichTextBox that I have used in the past. It's spliced together from code found here at Stack Overflow and the internet at large:
It adds new properties such as SelectionBold, SelectionItalic, etc. where you can apply the attribute and not lose the other formatting of the text.
You can pass the new font name while keeping other values intact by using the existing richtextbox font properties. For changing only font name of a selected text, you need to do:
Note that above code will only work, if all the selected text has same formatting (font size, style etc). This is detected by checking the SelectionFont property first, it will be null if the selection contains a mix of styles.
Now to change the font name of all the contents of richtextbox while keeping other formatting intact, you need to loop through all the characters of the richtextbox and apply font name one by one.
This will change the font property of the selected text.
Sample:
You can pass in new values for whatever parameter you want and use the
rtb
properties to preserve other values. For example, if you want to change thefont family
but want to preserve thefont size
, this is what you'd do:This will change the
SelectionFont
family tofontName
but preserves the font size. You can follow the same pattern for other overloads.