JavaScript Editor JavaScript Editor     JavaScript Debugger

Previous Section Next Section

Main Page

Creating Bold, Italic, Underlined, and Strikeout Text

Plenty of programmers know about rich text boxes, but few know how to actually format text in them (partially because everything has changed here from VB6, too). To work with rich text boxes, see the RichTextBoxes example on the CDROM. This example displays three rich text boxes and several buttons, as you see in Figure 5.8.

Figure 5.8: The RichTextBoxes example.

Note the top right rich text box in Figure 5.8, which is displaying formatted text. How does it add formatting like that? First, you select the text you want to format, which I do with the Find method, setting the return value of that method to the SelectionStart property. That selects the text to format.


You also can use the text box and rich text box Select method to select text, passing it the start and end location of the text to select.

Next, you need to create a new Font object to assign to the rich text box's SelectionFont property (which sets the font of the selected text). You can use Font objects to set the typeface and size of text, and you also can set font style using members of the FontStyle enumeration-for example, italic text is FontStyle.Italic, bold text is FontStyle.Bold, and so on. To preserve the other aspects of the text in the rich text box, I'll get the current font used in that control from its Font property, then use the Font class's constructor to base a new font on the current font while also setting a new attribute, such as italics, bolding, and so on. That looks like this:

Private Sub Button1_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles Button1.Click
    RichTextBox1.SelectionStart = RichTextBox1.Find("italic")
    Dim ItalicFont As New Font(RichTextBox1.Font, FontStyle.Italic)
    RichTextBox1.SelectionFont = ItalicFont

    RichTextBox1.SelectionStart = RichTextBox1.Find("bold")
    Dim BoldFont As New Font(RichTextBox1.Font, FontStyle.Bold)
    RichTextBox1.SelectionFont = BoldFont

    RichTextBox1.SelectionStart = RichTextBox1.Find("underlined")
    Dim UnderlineFont As New Font(RichTextBox1.Font, FontStyle.Underline)
    RichTextBox1.SelectionFont = UnderlineFont

    RichTextBox1.SelectionStart = RichTextBox1.Find("strikeout")
    Dim StrikeoutFont As New Font(RichTextBox1.Font, FontStyle.Strikeout)
    RichTextBox1.SelectionFont = StrikeoutFont
End Sub

The second button in the RichTextBoxes example copies this text with formatting intact to the middle rich text box (as you can see in Figure 5.8), using the kind of code discussed in the previous topic:

Private Sub Button2_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles Button2.Click
    RichTextBox2.Rtf = RichTextBox1.Rtf
End Sub
Previous Section Next Section

JavaScript Editor Free JavaScript Editor     JavaScript Editor