首页 文章

Winforms RichtextBox粗体/斜体/下划线格式问题

提问于
浏览
4

从 Headers 中可以看出,我在RichTexBox控件中为选定文本分配和删除格式样式时遇到了一些问题 .

我知道如何单独制作文字粗体/斜体/下划线,但不是这些的组合 . 我知道可以通过角色实现这个角色的方法,但这在界面上看起来很耗时 . 如果它可以在Wordpad中毫不费力地完成,我相信它可以在这里实现!

是否没有这样的方法或存在的方法可以让我"add"或"remove"来自 RichTextBox.SelectedFont

2 回答

  • 7

    我不得不像你必须那样思考 . 我觉得这是一个老帖子 . 但是,对于那些可能遇到同样问题的人 . 您不能将字体样式,字体系列,...应用于字符串,除非您逐个字符地迭代,因此您可以获得SelectionFont . 这是可以帮助您的方法:

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

    有关如何创建自定义richtexBox控件的更多详细信息,请转到http://how-to-code-net.blogspot.ro/2014/01/how-to-make-custom-richtextbox-control.html

  • 0

    除非我完全误解了这个问题

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

相关问题