Chapter 7. Using RichTextBoxes

The TextBox control lets the user enter text and that's about it. It can display its text in different colors and fonts, but it cannot give different pieces of text different properties. The TextBox is intended to let the user enter a simple string, like a name or street address, and little more.

The RichTextBox is a much more powerful control. It can display different pieces of text with different colors, fonts, and styles. It can adjust paragraph indentation and make bulleted lists. It can even include pictures. It's not as powerful as a full-featured word processor, such as Microsoft Word or OpenOffice's Writer, but it can produce a much more sophisticated result than the TextBox.

In this lesson you learn more about the RichTextBox control and how to use it. You have a chance to experiment with the control, and you use it to add enough functionality to the SimpleEdit program to finally make the program useful.

USING RICHTEXTBOX PROPERTIES

To change the appearance of the text inside a RichTextBox, you first select the text that you want to change, and then you set one of the control's properties to modify the text.

To select the text, you use the control's SelectionStart and SelectionLength properties to indicate where the text begins and how many letters it includes. Note that the letters are numbered starting with 0. (In fact, almost all numbering starts with 0 in Visual Basic.) For example, setting SelectionStart = 0 and SelectionLength = 1 selects the control's first letter.

After you select the text, you set one of the RichTextBox's properties to the value that you want the text to have.

For example, the following code makes the RichTextBox named rchContent display some text and color the word "red":

rchContent.Text = "Some red text"
rchContent.SelectionStart = 5
rchContent.SelectionLength = 3
rchContent.SelectionColor = Color.Red

Table 7-1 lists properties that you can use to change the text's appearance.

Table 7.1. TABLE 7-1

PROPERTY

PURPOSE

SelectionAlignment

Aligns the selection's paragraph on the left, center, or right.

SelectionBackColor

Sets the selection's background color.

SelectionBullet

Determines whether the selection's paragraph is bulleted.

SelectionCharOffset

Determines whether the selection is superscript (offset > 0), subscript (offset < 0), or normal (offset = 0).

SelectionColor

Sets the selection's color.

SelectionFont

Sets the selection's font.

SelectionHangingIndent

The first line in the selection's paragraph is indented normally and then subsequent lines in the paragraph are indented by this amount.

SelectionIndent

All lines are indented by this amount.

SelectionProtected

Marks the selected text as protected so the user cannot modify it.

SelectionRightIndent

All lines are indented on the right by this amount.

The FontFeatures example program shown in Figure 7-1 demonstrates properties that change the appearance of text within a paragraph. These include the SelectionBackColor, SelectionCharOffset, SelectionColor, and SelectionFont.

FIGURE 7-1

Figure 7.1. FIGURE 7-1

FIGURE 7-2

Figure 7.2. FIGURE 7-2

The ParagraphFeatures program shown in Figure 7-2 demonstrates properties that change the way paragraphs are displayed. These include SelectionIndent, SelectionHangingIndent, SelectionRightIndent, SelectionBullet, and SelectionAlignment.

Note

Both the FontFeatures and ParagraphFeatures sample programs are available as part of the Lesson07 download at www.wrox.com or www.vb-helper.com/24hourvb.html.

Table 7-2 summarizes four additional properties that change the text displayed by the control that deserve special mention.

Table 7.2. TABLE 7-2

PROPERTY

PURPOSE

Text

Gets or sets the control's complete text without any formatting properties.

Rtf

Gets or sets the control's Rich Text Format (RTF) contents. This includes the text plus RTF formatting codes that define how the text should be displayed.

SelectedText

Gets or sets the selection's text.

SelectedRtf

Gets or sets the selection's text and RTF codes.

GIVING THE USER CONTROL

Allowing the user to change text settings is easy. When the user selects text in the control, the RichTextBox sets its SelectionStart and SelectionLength properties accordingly. All you need to do is set the appropriate property (for example, SelectionColor) and the selected text is updated.

The SetTextProperties example program shown in Figure 7-3 (and available as part of the Lesson 7 code download) uses this technique to let the user control text color, character offset, and paragraph alignment. Select text and then click the tool strip buttons to change the text's properties.

FIGURE 7-3

Figure 7.3. FIGURE 7-3

The following code shows how the program changes the currently selected text to have a black background and white foreground:

Private Sub btnReversedColors_Click() Handles btnReversedColors.Click
    rchContent.SelectionColor = Color.White
rchContent.SelectionBackColor = Color.Black
End Sub

The program's other buttons work similarly.

USING RICHTEXTBOX METHODS

Lesson 2 briefly described properties, methods, and events. Other lessons have also worked with many properties and events. In fact, most of the event handlers I've discussed in the lessons so far catch an event and change a property in response.

Though you've worked with many properties and events, the only method you've seen is the form's Close method, which makes the form go away. For example, the following code closes the form that executes it:

Me.Close()

The RichTextBox provides many new methods that are helpful for building a text editing program. Table 7-3 summarizes some of the most useful.

Table 7.3. TABLE 7-3

METHOD

PURPOSE

Clear

Clears all text from the control.

Copy

Copies the current selection into the clipboard.

Cut

Cuts the current selection onto the clipboard.

DeselectAll

Deselects all text by setting SelectionLength = 0.

LoadFile

Loads the control's text from a file with one of various formats such as RTF or plain text.

Paste

Pastes whatever is in the clipboard into the current selection. This can be anything that the RichTextBox understands, such as text, RTF formatted text, or an image.

Redo

Redoes the previously undone command.

SaveFile

Saves the control's text into a file in one of various formats, such as RTF or plain text.

SelectAll

Selects all of the control's text by setting SelectionStart = 0 and SelectionLength equal to the text's length.

Undo

Undoes the most recent change.

The following code shows how a program can use the LoadFile method. The first parameter gives the name of the file, which can be relative to the program's current directory or a full path. The second parameter gives the type of file.

rchContent.LoadFile("Test.rtf", RichTextBoxStreamType.RichText)

The following code shows how a program can use the SaveFile method. As with LoadFile, the first parameter gives the file's name and the second gives its type.

rchContent.SaveFile("Test.rtf", RichTextBoxStreamType.RichText)

TRY IT

In this Try It, you add functionality to some of the SimpleEdit program's menu items and tool strip buttons. You use the RichTextBox properties and methods to implement the commands in the Edit menu: Undo, Redo, Copy, Cut, Paste, Delete, and Select All. (This also makes the corresponding buttons work at no extra charge.)

Note

You can download the code and resources for this Try It from the book's web page at www.wrox.com or www.vb-helper.com/24hourvb.html. You can find them in the Lesson07 folder in the download.

Lesson Requirements

In this lesson:

  • Copy the SimpleEdit program you built in Lesson 6, Exercise 5.

  • Add code to handle the Edit menu's commands.

    • Add Undo code.

    • Add Redo code.

    • Add Copy code.

    • Add Cut code.

    • Add Paste code.

    • Add Delete code.

    • Add Select All code.

Hints

  • For the Delete menu item, simply set the control's SelectedText property to an empty string ("").

Step-by-Step

  • Copy the SimpleEdit program you built in Lesson 6, Exercise 5 (or download Lesson 6's version from the book's web site).

  • Add code to handle the Edit menu's commands.

    1. Open the program's form in the Form Designer. Click the MenuStrip, expand the Edit menu, and double-click the Undo menu item.

    2. Replace the placeholder call to MessageBox.Show with the following line of code so the event handler looks like this:

      Private Sub mnuEditUndo_Click() _
       Handles mnuEditUndo.Click, btnUndo.Click
          rchDocument.Undo()
      End Sub
    3. Repeat the previous two steps for the other Edit menu items invoking the Redo, Copy, Cut, Paste, and SelectAll commands.

    4. For the Delete menu item, set the control's SelectedText property to an empty string ("").

When you finish, test the program's new features. One of the RichTextBox's more remarkable features is its ability to paste different kinds of items from the clipboard. For example, copy a picture to the clipboard and then use the program to paste it into the RichTextBox.

Note

Please select Lesson 7 on the DVD to view the video that accompanies this lesson.

EXERCISES

  1. (SimpleEdit) Copy the SimpleEdit program you built for the Try It and add simple code to handle the File menu's New, Open, and Save commands. For the New command, simply clear the RichTextBox. For the Open and Save commands, just load and save the file Test.rtf. (The program will create the file the first time you save. If you try to open the file before it exists, the program will crash, so don't use Open before you use Save.) Lesson 8 explains how to use File Open and Save dialogs to let the user pick the file that should be opened or saved.

  2. (SimpleEdit) Copy the SimpleEdit program you built for Exercise 1 and add code to handle the Format menu's commands (except for the Font command, which is covered in Lesson 8). Remove the placeholder MessageBox.Show commands.

    Hints:

    • Keep the code that manages the menu items and tool strip buttons. For example, keep the code that ensures only one alignment menu item and button are selected at a time.

    • When the user clicks a color button, copy the appropriate color to the btnTextColor and btnBackgroundColor buttons' ForeColor and BackColor properties.

    • To set the foreground color, use the color stored in btnTextColor.ForeColor.

    • To set the background color, use the color stored in btnBackgroundColor.BackColor.

    • Set the control's SelectionBullet property to the value of the bullet button's Checked property like this:

      rchDocument.SelectionBullet = btnBullet.Checked
    • Make the indentation commands (None, Hanging, Left, Right, and Both) reset any other indentations. For example, the Hanging command should set the SelectionIndent and SelectionRightIndent properties to 0 as in the following code:

      rchDocument.SelectionIndent = 0
      rchDocument.SelectionRightIndent = 0
      rchDocument.SelectionHangingIndent = 0
  3. The SimpleEdit program allows only the indentation styles None, Hanging, Left, Right, and Both. It doesn't allow other combinations such as Hanging plus Left. Build a program that uses tool strip buttons to let the user select each of the indentation properties (Hanging, Left, and Right) individually. Provide a fourth button to clear all the indentation properties.

Note

You can find solutions to this lesson's exercises in the Lesson07 folder inside the download available on the book's web site at www.wrox.com or www.vb-helper.com/24hourvb.html.

EXERCISES
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset