Toggling Font Styles in the RichTextBox Control

I'm sure it made sense to someone not to be able to modify styles on an existing font in .NET, but it always surprises me. In addition, the example in the documentation for the RichTextBox.SelectionFont property is pretty, well, broken. They include a ToggleFont method which supposedly toggles the state of the boldness of the selection. Unfortunately, it doesn't handle the text already having other attributes (italic, underline) and does its work awfully clumsily. In case you need this behavior, here's the procedure I came up with:

Private Sub ToggleFormat(ByVal rtb As RichTextBox, ByVal newStyle As FontStyle)
  If rtb.SelectionFont IsNot Nothing Then
    Dim currentFont As Font = rtb.SelectionFont
    Dim currentFontStyle As FontStyle = currentFont.Style
    Dim newFontStyle As FontStyle

    If (currentFontStyle And newStyle) = newStyle Then
      newFontStyle = currentFontStyle And Not newStyle
    Else
      newFontStyle = currentFontStyle Or newStyle
    End If

    rtb.SelectionFont = New Font(currentFont, newFontStyle)
  End If
End Sub

The issue is that it's not clear from the example, or from playing, that the font style is a set of bits (which makes sense, obviously, once you think about it). Setting and removing a font style is just a matter of setting and clearing bits. Therefore, the cleaner ToggleFormat.

Published Monday, February 20, 2006 9:10 PM by KenG

Comments

Wednesday, February 22, 2006 5:11 AM by In the Minority (Ken Getz)

# More on Toggling Font Styles

Soon after posting the previous item, my VB pal from down under, Bill McCarthy,  responded quickly...