VB.NET - RichTextBox - Apply formatting to selecte

2019-07-15 14:16发布

I have a RichTextBox control 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.

2条回答
霸刀☆藐视天下
2楼-- · 2019-07-15 14:27

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.

查看更多
\"骚年 ilove
3楼-- · 2019-07-15 14:52

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

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

Dim bfont As New Font(RichTextBoxFoo.Font, FontStyle.Bold)
RichTextBoxFoo.SelectionFont = bfont
查看更多
登录 后发表回答