views:

5234

answers:

2

Hello, this may be n00by, but, I have this simple question:

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  A: 

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
ahockley
Oh yeah and how to if the button is unchecked, the font returns normal?
+1  A: 

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.

VanSkalen
Ok, it worked for turning on/off, thanks.