Winforms RichtextBox Bold / Italic / Underlined Formatting Question

As you can tell from the name, I have a slight problem with assigning and deleting format styles to and from the selected text in the RichTexBox control.

I know how to make a text individually Bold / Italic / underline, but not a combination of them. I know the ways that this character can achieve by character, but it would seem to be time-consuming on the interface. If it can be easily done in Wordpad, I am sure that it can be done here!

Is there a method or one that exists that can allow me to β€œadd” or β€œremove” a style from RichTextBox.SelectedFont ?

+4
source share
2 answers

If I do not completely understand the question

// Get the current text selection or to text entered after the insertion point. // Build new font based on the selection font, make it both Bold and Underline // Apply new font to currently selected text (or for new text at insertion point Font currFont = richTextBox.SelectionFont; Font boldUnderFont = new Font(currFont, FontStyle.Bold | FontStyle.Underline); richTextBox.SelectionFont = boldUnderFont; 
+7
source

I had to do the same as you. I see this is an old post. However, for those who may face the same problem. You cannot apply a font style, a font family, ... to a string unless you repeat a character by character, and you can get a SelectionFont. This is a way that can help you:

 /// <summary> /// Changes a font from originalFont appending other properties /// </summary> /// <param name="originalFont">Original font of text /// <param name="familyName">Target family name /// <param name="emSize">Target text Size /// <param name="fontStyle">Target font style /// <param name="enableFontStyle">true when enable false when disable /// <returns>A new font with all provided properties added/removed to original font</returns> private Font RenderFont(Font originalFont, string familyName, float? emSize, FontStyle? fontStyle, bool? enableFontStyle) { if (fontStyle.HasValue && fontStyle != FontStyle.Regular && fontStyle != FontStyle.Bold && fontStyle != FontStyle.Italic && fontStyle != FontStyle.Underline) throw new System.InvalidProgramException("Invalid style parameter to ChangeFontStyleForSelectedText"); Font newFont; FontStyle? newStyle = null; if (fontStyle.HasValue) { if (fontStyle.HasValue && fontStyle == FontStyle.Regular) newStyle = fontStyle.Value; else if (originalFont != null && enableFontStyle.HasValue && enableFontStyle.Value) newStyle = originalFont.Style | fontStyle.Value; else newStyle = originalFont.Style & ~fontStyle.Value; } newFont = new Font(!string.IsNullOrEmpty(familyName) ? familyName : originalFont.FontFamily.Name, emSize.HasValue ? emSize.Value : originalFont.Size, newStyle.HasValue ? newStyle.Value : originalFont.Style); return newFont; } 

More information on how to create your own richtexBox control can be found at http://how-to-code-net.blogspot.ro/2014/01/how-to-make-custom-richtextbox-control.html

0
source

All Articles