VB.NET - RichTextBox - Apply formatting to selected text

馋奶兔 提交于 2019-12-11 03:08:08

问题


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.


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/109032/vb-net-richtextbox-apply-formatting-to-selected-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!