Using RichTextBoxes - The Visual Studio IDE and Controls - C# 24-Hour Trainer (2015)

C# 24-Hour Trainer (2015)

Section I

The Visual Studio IDE and Controls

Lesson 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 very 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 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 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 C#.) 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 selected text to have.

For example, the following code makes the RichTextBox named contentRichTextBox display some text and colors the word “red”:

contentRichTextBox.Text = "Some red text";

contentRichTextBox.SelectionStart = 5;

contentRichTextBox.SelectionLength = 3;

contentRichTextBox.SelectionColor = Color.Red;

Table 7.1 lists properties that you can use to change the text's appearance.

Table 7.1




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


Sets the selection's background color.


Determines whether the selection's paragraph is bulleted.


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


Sets the selection's color.


Sets the selection's font.


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


All lines are indented by this amount.


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


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.

Screenshot of Font Features window displaying several text with different fonts.

Figure 7.1

For example, the following code shows how the FontFeatures program sets the background color behind the word “BackColor”:

contentRichTextBox.SelectionStart = 41;

contentRichTextBox.SelectionLength = 9;

contentRichTextBox.SelectionBackColor = Color.Yellow;

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.

Image described by surrounding text.

Figure 7.2

For example, the following code shows how the ParagraphFeatures program gives the second paragraph a 20 pixel hanging indent:

contentRichTextBox.SelectionStart = 82;

contentRichTextBox.SelectionLength = 1;

contentRichTextBox.SelectionHangingIndent = 20;

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

Table 7.2




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


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.


Gets or sets the selection's text.


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 uses this technique to let the user control text color, character offset, and paragraph alignment. Select some text and then click the tool strip buttons to change the text's properties.

Image described by surrounding text.

Figure 7.3

For example, the following code shows how the SetTextProperties program changes the currently selected text to have a black background and white foreground:

private void reverseColorsButton_Click(object sender, EventArgs e)


contentRichTextBox.SelectionBackColor = Color.Black;

contentRichTextBox.SelectionColor = Color.White;


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.

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


The RichTextBox provides many new methods that are quite helpful for building a text editing program. Table 7.3 summarizes some of the most useful of those methods.

Table 7.3




Clears all text from the control.


Copies the current selection into the clipboard.


Cuts the current selection into the clipboard.


Deselects all text by setting SelectionLength = 0.


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


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.


Redoes the previously undone command.


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


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


Undoes the most recent change.

The following code shows how a program can use the LoadFile method:

contentRichTextBox.LoadFile("Test.rtf", RichTextBoxStreamType.RichText);

The first parameter passed into LoadFile 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. The RichTextBoxStreamType enumeration lists file types that you can use. The choices you can use to load files are PlainText, RichText, and UnicodePlainText.

Typing Tips

When you type contentRichTextBox.LoadFile(, IntelliSense) and displays the popup shown in Figure 7.4 to show the parameters that the LoadFile method expects. (Visual Studio adds red squiggly underlines because the statement isn't finished yet. Until I finish typing the statement, Visual Studio flags it as an error.)

Image described by surrounding text.

Figure 7.4

You can choose from three different overloaded versions of the method, each taking different parameters. Overloaded versions of a method have the same name but take different parameters. You can use the up and down arrow keys to scroll through the method's available versions.

As you enter parameters, IntelliSense updates to describe the next parameter that it expects. Figure 7.5 shows the LoadFile method after I entered a filename for the first parameter. IntelliSense shows that the next parameter should be a value of typeRichTextBoxStreamType named fileType. IntelliSense even shows a short description of what the value means at the bottom (although it's not super informative).

Image described by surrounding text.

Figure 7.5

You could type in RichTextBoxStreamType followed by a dot to see a list of available choices, but there's an even easier (in other words, better) way to do this: press Ctrl+Space. That makes IntelliSense display a list of things that you might be trying to type. At this point, IntelliSense is smart enough to guess that you want to type RichTextBoxStreamType so it initially selects that type and even displays more information about it, as shown in Figure 7.6.

Image described by surrounding text.

Figure 7.6

Now you can press Tab to make IntelliSense fill in the highlighted value RichTextBoxStreamType for you.

Next, press the “.” key to see the list of choices shown in Figure 7.7, pick one, and press Tab to add it to the code. Finally, add a semicolon at the end of the line and you're done.

Image described by surrounding text.

Figure 7.7

I know this sounds like a big mess, but with a little practice it becomes surprisingly quick and easy. Typing everything by hand, I can enter the previous LoadFile statement in about 30 seconds. With IntelliSense's help, I can type the same line in under 10 seconds.

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:

contentRichTextBox.SaveFile("Test.rtf", RichTextBoxStreamType.RichText);

Using WPF Commands

A program can use commands to manipulate the contents of a RichTextBox. That control also provides commands that the user can invoke interactively. For example, the user can press Ctrl+E to center paragraphs.

Table 7.4 summarizes the most useful commands. The commands for the Windows Forms and WPF versions of the control differ slightly.

Table 7.4


Windows Forms


Align centered



Align justified


Align left



Align right












Decrease font size





Delete next word



Delete previous word



Increase font size








Subscript 2



Superscript 2



Toggle bold


Toggle insert



Toggle italic


Toggle underline



* In Windows Forms, Ctrl+Shift+L iterates through the available bullet and numbering styles.

** The subscript and superscript sequences are a bit confusing. For subscript, hold the Ctrl key and press +. For superscript, hold the Ctrl and Shift keys and press +. In WPF, those commands work only for OpenType fonts that come with subscript and superscript variants. Try the Palatino Linotype font. For more information on OpenType fonts,

Both controls provide additional navigation commands. For example, Ctrl+Right Arrow moves one word to the right and Ctrl+Down Arrow moves one paragraph downward.

The WPF control also provides a context menu that contains the Copy, Cut, and Paste commands.

For more information on the WPF control's commands, including the navigation commands, see

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.)

Lesson Requirements

In this lesson, you:

· Copy the SimpleEdit program you built in Lesson 6, Exercise 9.

· Replace the program's TextBox with a RichTextBox named contentRichTextBox.

· 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.


You can download the code and resources for this lesson from the website at


· For the Delete menu item, simply set the control's SelectedText property to an empty string: "".


· Copy the SimpleEdit program you built in Lesson 6, Exercise 9 (or download Lesson 6's version from the book's website).

· Replace the program's TextBox with a RichTextBox named contentRichTextBox.

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

3. private void editUndoMenuItem_Click(object sender, EventArgs e)

4. {

5. contentRichTextBox.Undo();


6. Repeat the previous two steps for the other Edit menu items. The following code shows the new event handlers:

7. private void editUndoMenuItem_Click(object sender, EventArgs e)

8. {

9. contentRichTextBox.Undo();

10. }

11. private void editRedoMenuItem_Click(object sender, EventArgs e)

12. {

13. contentRichTextBox.Redo();

14. }

15. private void editCopyMenuItem_Click(object sender, EventArgs e)

16. {

17. contentRichTextBox.Copy();

18. }

19. private void editCutMenuItem_Click(object sender, EventArgs e)

20. {

21. contentRichTextBox.Cut();

22. }

23. private void editPasteMenuItem_Click(object sender, EventArgs e)

24. {

25. contentRichTextBox.Paste();

26. }

27. private void editDeleteMenuItem_Click(object sender, EventArgs e)

28. {

29. contentRichTextBox.SelectedText = "";

30. }

31. private void editSelectAllMenuItem_Click(object sender, EventArgs e)

32. {

33. contentRichTextBox.SelectAll();


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 theRichTextBox.


1. [WPF, SimpleEdit] Repeat the Try It using the WPF program you built for Lesson 6's Exercise 10. Hint: To delete the current selection, use the statement contentRichTextBox.Selection.Text = "".

2. [SimpleEdit] Copy the program you built for the Try It and add simple code to handle the File menu's New, Open, Save, and Exit commands. For the New command, simply clear the RichTextBox. (Hint: Use the Clear method.)

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.

3. [WPF, SimpleEdit] Repeat Exercise 2 using the program you built for Exercise 1. Hints:

· One way to clear the control's contents is to use the following code:

· contentRichTextBox.SelectAll();

contentRichTextBox.Selection.Text = "";

· The preceding code works but is rather slow if the control contains a lot of text. The following code is more complicated but more efficient:

· TextRange range = new TextRange(

· contentRichTextBox.Document.ContentStart,

· contentRichTextBox.Document.ContentEnd);

range.Text = "";

· To load the saved file, use the following code (sorry, but WPF's version of the RichTextBox is a bit more complicated):

· TextRange range = new TextRange(

· contentRichTextBox.Document.ContentStart,

· contentRichTextBox.Document.ContentEnd);

· using (System.IO.Stream stream =

· new System.IO.FileStream("Test.rtf", System.IO.FileMode.Open))

· {

· range.Load(stream, DataFormats.Rtf);


· To save text into a file, use the following code:

· TextRange range = new TextRange(

· contentRichTextBox.Document.ContentStart,

· contentRichTextBox.Document.ContentEnd);

· using (System.IO.Stream stream =

· new System.IO.FileStream("Test.rtf", System.IO.FileMode.Create))

· {

· range.Save(stream, DataFormats.Rtf);


4. [SimpleEdit] Copy the SimpleEdit program you built for Exercise 2 and add code to handle the Format menu's commands (except for the Font command and color commands, which are covered in Lesson 8).


· To turn bullets on and off, use the statement contentRichTextBox.SelectionBullet = formatBulletMenuItem.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:

· contentRichTextBox.SelectionIndent = 0;

· contentRichTextBox.SelectionRightIndent = 0;

contentRichTextBox.SelectionHangingIndent = 20;

5. [WPF, SimpleEdit] Copy the WPF SimpleEdit program you built for Exercise 3 and add code to handle the Format menu's alignment and bullet commands. Hints:

· To turn bullets on and off, use the statement EditingCommands.ToggleBullets.Execute(null, contentRichTextBox).

· Use similar EditingCommands methods for the alignment commands.

6. 6 [SimpleEdit] Copy the SimpleEdit program you built for Exercise 4 and add code to handle the toolbar's color commands.

7. The SimpleEdit program allows only the indentation styles None, Hanging, Left, Right, and Both. It doesn't allow other combinations such as Hanging plus Right. 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 of the indentation properties.

8. Make a program with two menus and a RichTextBox. The File menu should contain the usual Exit command. The Font menu should contain the items Small, Medium, and Large and should use small, medium, and large fonts, respectively. When the user selects one of those items, the program should set the RichTextBox's selected text to use that item's font.

9. [Hard] Make a program with a RichTextBox and a toolbar containing Undo and Redo buttons. Initially disable the buttons. Whenever the user changes the RichTextBox's text (catch the TextChanged event) or clicks one of the buttons, use the RichTextBox control'sCanUndo and CanRedo properties to enable or disable the buttons. Verify that this works as expected when you click the buttons or press Ctrl+Z or Ctrl+Y. Also make sure it works if you press Ctrl+V to paste into the RichTextBox.


Please select the videos for Lesson 7 online at