visual-studio VB.NET - RichTextBox - 将格式应用于所选文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/109032/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 16:33:50  来源:igfitidea点击:

VB.NET - RichTextBox - Apply formatting to selected text

vb.netvisual-studiowinformsformattingtext-editor

提问by VanSkalen

I have a RichTextBoxcontrol on my form. I also have this button, labeled Bold, that I want, if someone selects text in the RichTextBox, then presses the button, the selected text turns bold.Any way to do that? Simple, everyday task for end users. Thanks.

我的表单上有一个RichTextBox控件。我也有我想要的这个标记为Bold 的按钮,如果有人在RichTextBox 中选择文本,然后按下按钮,所选文本将变为粗体。有没有办法做到这一点?最终用户的简单日常任务。谢谢。

回答by ahockley

You'll want to use the .SelectionFont property of the RichTextBox and assign it a Font object with the desired styles.

您需要使用 RichTextBox 的 .SelectionFont 属性并为其分配一个具有所需样式的 Font 对象。

Example - this code would be in the event handler for the button:

示例 - 此代码将位于按钮的事件处理程序中:

Dim bfont As New Font(RichTextBoxFoo.Font, FontStyle.Bold)
RichTextBoxFoo.SelectionFont = bfont

回答by VanSkalen

A variation on the above that takes into consideration switching bold on/off depending on the currently selected text's font info:

考虑根据当前选定文本的字体信息打开/关闭粗体的上述变体:

    With Me.rtbDoc
        If .SelectionFont IsNot Nothing Then
            Dim currentFont As System.Drawing.Font = .SelectionFont
            Dim newFontStyle As System.Drawing.FontStyle

            If .SelectionFont.Bold = True Then
                newFontStyle = currentFont.Style - Drawing.FontStyle.Bold
            Else
                newFontStyle = currentFont.Style + Drawing.FontStyle.Bold
            End If

            .SelectionFont = New Drawing.Font(currentFont.FontFamily, currentFont.Size, newFontStyle)
        End If
    End With

It may need cleaned up a bit, I pulled this from an older project.

它可能需要清理一下,我从一个旧项目中提取了它。