问题
As you can tell from the title, Im having a bit of issue regarding assigning and removing format styles to and from selected text in the RichTexBox control.
I know how to make text individually Bold/Italic/Underline, but not a combination of these. I know of ways that can achieve this character by character, but this would seem time-consuming on the interface. If it can be effortlessly done in Wordpad, Im sure it can be achieved here!
Is there no such method or such that exists that can allow me to "add" or "remove" a style from RichTextBox.SelectedFont?
回答1:
Unless I am completely misunderstanding 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;
回答2:
I had to do same think as you had to do. I see it is an old post. However, for those that might encounter same issue. You can not apply a font style, font family, ..., to a string unless you iterate character by character and thus you can get SelectionFont. This is the method 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;
}
For more details about how to make a custom richtexBox control you can go to http://how-to-code-net.blogspot.ro/2014/01/how-to-make-custom-richtextbox-control.html
来源:https://stackoverflow.com/questions/1252040/winforms-richtextbox-bold-italic-underline-formatting-issue