The RichTextBox Control
The RichTextBox control allows the user to display, enter, and edit text while also providing more advanced formatting features than the conventional TextBox control.
Following is a general description of the RichTextBox (RTB) control along with summaries of its pertinent properties, methods, and events; all compiled from the MSDN help files. This article concludes with a sample application that uses the RTB to implement a text editor similar to WordPad.
General Description
The RichTextBox control provides a number of properties you can use to apply formatting to any portion of text within the control. To change the formatting of text, it must first be selected. Only selected text can be assigned character and paragraph formatting. Using these properties, you can make text bold or italic, change the color, and create superscripts and subscripts. You can also adjust paragraph formatting by setting both left and right indents, as well as hanging indents.
The RichTextBox control opens and saves files in both the RTF format and regular ASCII text format. You can use methods of the control (LoadFile and SaveFile) to directly read and write files, or use properties of the control such as SelRTF and TextRTF in conjunction with Visual Basic's file input/output statements.
The RichTextBox control supports object embedding by using the OLEObjects collection. Each object inserted into the control is represented by an OLEObject object. This allows you to create documents with the control that contain other documents or objects. For example, you can create a document that has an embedded Microsoft Excel spreadsheet or a Microsoft Word document or any other OLE object registered on your system. To insert objects into the RichTextBox control, you simply drag a file (from the Windows 95 Explorer for example), or a highlighted portion of a file used in another application (such as Microsoft Word), and drop the contents directly onto the control.
The RichTextBox control supports both clipboard and OLE drag/drop of OLE objects. When an object is pasted in from the clipboard, it is inserted at the current insertion point. When an object is dragged and dropped into the control, the insertion point will track the mouse cursor until the mouse button is released, causing the object to be inserted. This behavior is the same as Microsoft Word.
To print all or part of the text in a RichTextBox control use the SelPrint method.
Because the RichTextBox is a data-bound control, you can bind it with a Data control to a Binary or Memo field in a Microsoft Access database or a similar large capacity field in other databases (such as a TEXT data type field in SQL Server).
The RichTextBox control supports almost all of the properties, events and methods used with the standard TextBox control, such as MaxLength, MultiLine, ScrollBars, SelLength, SelStart, and SelText. Applications that already use TextBox controls can easily be adapted to make use of RichTextBox controls. However, the RichTextBox control doesn't have the same 64K character capacity limit of the conventional TextBox control.
The RichTextBox control must be added to the toolbox via the Components dialog box, as shown below. This dialog box is accessed via the Project menu, Components item. Once you check "Microsoft Rich Textbox Control 6.0" and click OK, the control is added to your toolbox (also shown below, circled). Then you can double-click it to make it appear on your form, as you would with any other control.
The Components Dialog Box |
RichTextBox Control Added to Toolbox |
|
Properties of the RichTextBox Control:
Property |
Description |
||||||||||
AutoVerbMenu |
Returns or sets a Boolean value that determines if a pop-up menu containing the RTB's verbs (Cut, Copy Paste) is displayed when the user clicks the RTB control with the right mouse button. When this property is set to True, Click events and MouseDown events don't occur when the RTB control is clicked with the right mouse button. In order to display your own menus, the AutoVerbMenu property must be set to False. |
||||||||||
BulletIndent |
Returns or sets the amount of indent (Integer) used in the RTB when SelBullet is set to True. The units for the value is based on the ScaleMode setting (twips, pixels, etc.) for the form that contains the RTB. The BulletIndent property returns Null if the selection spans multiple paragraphs with different margin settings. |
||||||||||
DisableNoScroll |
Returns or sets a Boolean value that determines whether scroll bars in the RichTextBox control are disabled. The DisableNoScroll property is ignored when the ScrollBars property is set to 0 (None). However, when ScrollBars is set to 1 (Horizontal), 2 (Vertical), or 3 (Both), individual scroll bars are disabled when there are too few lines of text to scroll vertically or too few characters of text to scroll horizontally in the RichTextBox control. |
||||||||||
FileName |
Returns or sets the filename of the file loaded into the RichTextBox control. Only the names of text files or valid .rtf files can be specified for this property. |
||||||||||
HideSelection |
Returns a Boolean value that determines whether selected text appears highlighted when the RTB loses focus. |
||||||||||
Locked |
Returns or sets a Boolean value indicating whether the contents of the RTB can be edited. (Setting Locked to True makes the contents of the RTB read-only - however, the content can still be modified by code.) |
||||||||||
MaxLength |
Returns or sets a value (Long) indicating whether there is a maximum number of characters a RichTextBox control can hold and, if so, specifies the maximum number of characters. The default for the MaxLength property is 0, indicating no maximum other than that created by memory constraints on the user's system. Any number greater than 0 indicates the maximum number of characters. Use the MaxLength property to limit the number of characters a user can enter in a RichTextBox. If text that exceeds the MaxLength property setting is assigned to a RichTextBox from code, no error occurs; however, only the maximum number of characters is assigned to the Text property, and extra characters are truncated. Changing this property doesn't affect the current contents of a RichTextBox, but will affect any subsequent changes to the contents. |
||||||||||
MultiLine |
Returns or sets a Boolean value indicating whether the RTB can accept and display multiple lines of text. (If False, carriage returns are ignored and text is restricted to a single line.) A multiple-line RichTextBox control wraps text as the user types text extending beyond the text box. Scroll bars can be added to to a larger RichTextBox control using the ScrollBars property. If no horizontal scroll bar is specified, the text in a multiple-line RichTextBox automatically wraps. Note: On a form with no default button, pressing ENTER in a multiple-line RichTextBox control moves the focus to the next line. If a default button exists, you must press CTRL+ENTER to move to the next line. This property is read-only at run-time. |
||||||||||
OLEObjects |
Every embedded OLE object created in the RichTextBox control is represented in the OLEObjects collection. You can manually add objects to the OLEObjects collection at run time by using the Add method, or by dragging an object from the Windows Explorer into the RichTextBox control. The OLEObjects collection is a standard collection and supports the Add, Item, and Remove methods, as well as the Count property. |
||||||||||
RightMargin |
The RightMargin property is a Long value used to set the right most limit for text wrapping, centering, and indentation. Centering a paragraph is based on the left most part of the text portion(doesn't include borders) of the RichTextBox control and the RightMargin property. Also, when setting the SelRightIndent property, it will be based on the current setting of the RightMargin property. The default for the RightMargin property is 0 and will cause the control to set text wrapping equal to the right most part of the RichTextBox control so all text is viewable. Note: Setting this property to a very large value will essentially remove WordWrap. |
||||||||||
ScrollBars |
Returns or sets a value indicating whether the RTB has horizontal or vertical scroll bars. Read-only at run-time. Possible values are 0-rtfNone (default, no scroll bars shown), 1-rtfHorizontal (horizontal scroll bar only), 2-rtfVertical (vertical scroll bar only), or 3-rtfBoth (both horizontal and vertical scroll bars shown). For a RichTextBox control with setting 1 (Horizontal), 2 (Vertical), or 3 (Both), you must set the MultiLine property to True. At run time, the Windows automatically implements a standard keyboard interface to allow navigation in RichTextBox controls with the arrow keys (UP ARROW, DOWN ARROW, LEFT ARROW, and RIGHT ARROW), the HOME and END keys, and so on. Scroll bars are displayed only if the contents of the RichTextBox extend beyond the control's borders. If ScrollBars is set to False, the control won't have scroll bars, regardless of its contents. A horizontal scrollbar will appear only when the RightMargin property is set to a value that is larger than the width of the control. (The value can also be equal to, or slightly smaller than the width of the control.) |
||||||||||
SelAlignment |
Returns or sets a value that controls the alignment of the paragraphs in a RichTextBox control. Not available at design time. Possible values are Null (the current selection spans more than one paragraph with different alignments), 0-rtfLeft (default, the paragraph is aligned along the left margin), 1-rtfRight (the paragraph is aligned along the right margin), or 2-rtfCenter (the paragraph is centered between the left and right margins). The SelAlignment property determines paragraph alignment for all paragraphs that have text in the current selection or for the paragraph containing the insertion point if no text is selected. To distinguish between the values of Null and 0 when reading this property at run time, use the IsNull function with the If...Then...Else statement. For example:
|
||||||||||
SelBold, SelItalic, SelUnderline, SelStrikethru |
Boolean. Return or set font styles of the currently selected text in a RichTextBox control. The font styles include the following formats: Bold, Italic, Strikethru, and Underline. Not available at design time. Possible values are Null (the selection or character following the insertion point contains characters that have a mix of the appropriate font styles), True (all the characters in the selection or character following the insertion point have the appropriate font style), or False (none of the characters in the selection or character following the insertion point have the appropriate font style). These properties behave like the Bold, Italic, Strikethru, and Underline properties of a Font object. The RichTextBox control has a Font property and therefore the ability to apply font styles to all the text in the control through the properties of the control's Font object. Use these properties to apply font styles to selected text or to characters entered at the insertion point. Typically, you access these properties by creating a toolbar in your application with buttons to toggle these properties individually. To distinguish between the values of Null and False when reading these properties at run time, use the IsNull function with the If...Then...Else statement. For example:
|
||||||||||
SelBullet |
Returns or sets a value that determines if a paragraph in the RichTextBox control containing the current selection or insertion point has the bullet style. Not available at design time. Possible values are Null (the selection spans more than one paragraph and contains a mixture of bullet and non-bullet styles), True (the paragraphs in the selection have the bullet style), or False (the paragraphs in the selection do not have the bullet style). Use the SelBullet property to build a list of bulleted items in a RichTextBox control. To distinguish between the values of Null and False when reading this property at run time, use the IsNull function with the If...Then...Else statement. For example:
|
||||||||||
SelCharOffset |
Returns or sets a value that determines whether text in the RichTextBox control appears on the baseline (normal), as a superscript above the baseline, or as a subscript below the baseline. Not available at design time. Possible values are Null (the selection has a mix of characters with different offsets), zero (normal – the characters all appear on the normal text baseline), a positive integer (the characters appear above the baseline by the number of twips specified), or a negative integer (the characters appear below the baseline by the number of twips specified). To distinguish between the values of Null and 0 when reading this property at run time, use the IsNull function with the If...Then...Else statement. For example:
|
||||||||||
SelColor |
Returns or sets a value that determines the color of text in the RichTextBox control. Not available at design time. The value can be Null (the selected text contains a mixture of different color settings) or a Long representing the color of the selected text). If there is no text selected in the RichTextBox control, setting this property determines the color of all new text entered at the current insertion point. |
||||||||||
SelFontName |
Returns or sets the font used to display the currently selected text or the character(s) immediately following the insertion point in the RichTextBox control. Not available at design time. The SelFontName property returns Null if the selected text contains different fonts. |
||||||||||
SelFontSize |
Returns or sets a value that specifies the size of the font used to display text in a RichTextBox control. Not available at design time. The maximum value for SelFontSize is 2160 points. In general, you should change the SelFontName property before you set the size and style attributes. However, when you set TrueType fonts to smaller than 8 points, you should set the point size to 3 with the SelFontSize property, then set the SelFontName property, and then set the size again with the SelFontSize property. Note: Available fonts depend on your system configuration, display devices, and printing devices, and therefore may vary from system to system. The SelFontSize property returns Null if the selected text contains different font sizes. |
||||||||||
SelIndent, SelRightIndent, SelHangingIndent |
Returns or sets the margin settings for the paragraph(s) in a RichTextBox control that either contain the current selection or are added at the current insertion point. Not available at design time. The units for the value is based on the ScaleMode setting (twips, pixels, etc.) for the form that contains the RTB. For the affected paragraph(s), the SelIndent property specifies the distance between the left edge of the RichTextBox control and the left edge of the text that is selected or added. Similarly, the SelRightIndent property specifies the distance between the right edge of the RichTextBox control and the right edge of the text that is selected or added. The SelHangingIndent property specifies the distance between the left edge of the first line of text in the selected paragraph(s) (as specified by the SelIndent property) and the left edge of subsequent lines of text in the same paragraph(s). These properties return zero (0) if the selection spans multiple paragraphs with different margin settings. |
||||||||||
SelProtected |
Returns or sets a value which determines if the current selection is protected. Not available at design time. Possible values are Null (the selection contains a mix of the protected and non-protected characters), True (all the characters in the selection are protected), or False (none of the characters in the selection are protected). Protected text looks the same a regular text, but cannot be modified by the end-user. That is, the text cannot be changed during run time. This allows you to create forms with the RichTextbox control, and have areas that cannot be modified by the end user. |
||||||||||
SelStart, SelLength, SelText |
These properties aren't available at design-time. Use these properties for tasks such as setting the insertion point, establishing an insertion range, selecting substrings in a control, or clearing text. Used in conjunction with the Clipboard object, these properties are useful for copy, cut, and paste operations. When working with these properties:
|
||||||||||
SelRTF |
Returns or sets the text (in .rtf format) in the current selection of a RichTextBox control. Not available at design time. Setting the SelRTF property replaces any selected text in the RichTextBox control with the new string. This property returns a zero-length string ("") if no text is selected in the control. You can use the SelRTF property along with the Print function to write .rtf files. |
||||||||||
SelTabCount , SelTabs |
Returns or sets the number of tabs and the absolute tab positions of text in a RichTextBox control. Not available at design time. Syntax object.SelTabCount [= count] object.SelTabs(index) [= location] The SelTabCount and SelTabs properties syntaxes have these parts:
Remarks By default, pressing TAB when typing in a RichTextBox control causes focus to move to the next control in the tab order, as specified by the TabIndex property. One way to insert a tab in the text is by pressing CTRL+TAB. However, users who are accustomed to working with word processors may find the CTRL+TAB key combination contrary to their experience. You can enable use of the TAB key to insert a tab in a RichTextBox control by temporarily switching the TabStop property of all the controls on the Form object to False while the RichTextBox control has focus. For example:
Make sure to reset the TabStop property of the other controls when the RichTextBox control loses focus. |
||||||||||
TextRTF |
Returns or sets the text of a RichTextBox control, including all .rtf code. Setting the TextRTF property replaces the entire contents of a RichTextBox control with the new string. You can use the TextRTF property along with the Print function to write .rtf files. The resulting file can be read by any other word processor capable of reading RTF-encoded text. |
Methods of the RichTextBox Control:
The SelChange Event
Occurs when the current selection of text in the RichTextBox control has changed or the insertion point has moved. You can use the SelChange event to check the various properties that give information about the current selection (such as SelBold) so you can update buttons in a toolbar, for example.
Sample Application
The sample application for this article uses the RichTextBox control to implement a WordPad-like text editor (see the screen shot below):
This article does not contain a "blow by blow" description of the code for the sample application, but much can be learned by downloading the sample application and working with it.
The sample application incorporates many of the features of the RichTextBox discussed earlier in this article, and also incorporates the use of menus and controls discussed in the topics preceding this one (Toolbar, CommonDialog, StatusBar). Also, many of the concepts and techniques used for the File and Edit menu commands in the previous topic on building the basic text editor have been incorporated here.
Development of this sample application was not as straightforward as I would have hoped. Most of the trouble stemmed from the fact that the RichTextBox has built-in capabilities for basic text editing (such as support of keyboard shortcuts like Ctrl-X and Ctrl-V for cutting and pasting), causing conflicts when attempting to implement keyboard events and menu Edit commands (such as keyboard shortcuts not working at all, "double pasting", etc.). Related to cutting and pasting is the Clipboard object, which I could not get to always "do the right thing" when a mixture of text and graphics was involved. These issues were resolved by using a custom Clipboard class in lieu of the Clipboard object, and by using the API technique of subclassing to intercept some of the keyboard shortcuts. Another minor issue I encountered was that the toolbar would sometimes indicate that more than one alignment setting (left, center, right) was in effect at the same time – this problem was tracked to a known Microsoft bug in the toolbar (http://support.microsoft.com/kb/189666/EN-US) and was resolved by using the recommended workaround.
The sample application is a robust demo that shows you how to use many of the RichTextBox's features, as well as providing a "workout" with menus, the Toolbar, and the Common Dialog controls. Features that are not present in the sample application are advanced paragraph formatting and tab-setting. If you were inclined to enhance this application, that would be a good place to start. It would require getting familiar with the SelIndent, SelRightIndent, and SelHangingIndent properties of the RTB for the paragraph formatting and with the SelTabCount and SelTabs properties for tab-setting. In addition, you would have to come up with a way to display a ruler (possible suggestions for the ruler include using a PictureBox in conjunction with labels or lines, or by finding a freeware custom control).
Download the project files for the sample application here.