RichTextBox Control

The RichTextBox control allows the user to enter and edit text while also providing more advanced formatting features than the conventional TextBox control.

Syntax

RichTextBox

Remarks

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.

Distribution Note To use the RichTextBox control in your application, you must add the Richtx32.ocx file to the project. When distributing your application, install the Richtx32.ocx file in the user's Microsoft Windows SYSTEM directory. For more information on how to add a custom control to a project, see the Programmer's Guide.


Topic Not Found

No matching topic was found. Some possible reasons and remedies are as follows:

  • The file (.chm) that contains the destination topic is not in the expected location.

    Remedy: Rerun the MSDN Library Setup.

  • The file (.chm) that contains the current topic or destination topic is out-of-date and the link is no longer valid.

    Remedy: Install the latest version of the MSDN Library.

  • The MSDN Library CD is not in the CD-ROM drive.

    Remedy: Insert the MSDN Library CD into the CD-ROM drive.


OLEObjects Collection

An OLEObjects collection contains a collection of OLEObject objects.

Syntax

object.OLEObjects(index)

object.OLEObjects.Item(index)

The OLEObjects collection syntax has these parts:

Part | Description
object | An object expression that evaluates to an object in the Applies To list.
index | The value of either the Index property or the Key property which uniquely identifies the OLEObject object.

Remarks

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.


Supported RTF Codes (RichTextBox Control)

Supported RTF Codes

The RichTextBox control recognizes the following RTF (Rich Text Format) codes. All other RTF codes are ignored by the control when loading text.

RTF Code | Description | RTF Code | Description
- | OptionalHyphen | objcropl | CropLeft
\n | EndParagraph | objcropr | CropRight
\r | EndParagraph | objcropt | CropTop
_ | NonBreakingHyphen | objdata | ObjectData
| | FormulaCharacter | object | Object
~ | NonBreakingSpace | objemb | ObjectEmbedded
ansi | CharSetAnsi | objh | Height
b | Bold | objicemb | ObjectMacICEmbedder
bin | BinaryData | objlink | ObjectLink
blue | ColorBlue | objname | ObjectName
bullet | ANSI Character 149 | objpub | ObjectMacPublisher
cb | ColorBackground | objscalex | ScaleX
cell | Cell | objscaley | ScaleY
cf | ColorForeground | objsetsize | ObjectSetSize
colortbl | ColorTable | objsub | ObjectMacSubscriber
cpg | CodePage | objw | Width
deff | DefaultFont | par | EndParagraph
deflang | DefaultLanguage | pard | ParagraphDefault
deftab | DefaultTabWidth | pc | CharSetPc
deleted | Deleted | pca | CharSetPs2
dibitmap | PictureWindowsDIB | piccropb | CropBottom
dn | Down | piccropl | CropLeft
dy | TimeDay | piccropr | CropRight
emdash | ANSI Character 151 | piccropt | CropTop
endash | ANSI Character 150 | pich | Height
f | FontSelect | pichgoal | DesiredHeight
fbidi | FontFamilyBidi | picscalex | ScaleX
fchars | FollowingPunct | picscaley | ScaleY
fcharset | CharSet | pict | Picture
fdecor | FontFamilyDecorative | picw | Width
fi | IndentFirst | picwgoal | DesiredWidth
field | Field | plain | CharacterDefault
fldinst | FieldInstruction | pmmetafile | PictureOS2Metafile
fldrslt | FieldResult | pn | ParaNum
fmodern | FontFamilyModern | pnindent | ParaNumIndent
fname | RealFontName | pnlvlblt | ParaNumBullet
fnil | FontFamilyDefault | pntext | ParaNumText
fontemb | FontEmbedded | pntxta | ParaNumAfter
fontfile | FontFile | pntxtb | ParaNumBefore
fonttbl | FontTable | protect | Protect
footer | NullDestination (Footer) | qc | AlignCenter
footerf | NullDestination (Footer, first) | ql | AlignLeft
footerl | NullDestination (Footer, left) | qr | AlignRight
footerr | NullDestination (Footer, right) | rdblquote | ANSI Character 34
footnote | NullDestination (footnote) | red | ColorRed
fprq | Pitch | result | ObjectResult
froman | FontFamilyRoman | revauth | RevAuthor
fs | FontSize | revised | Revision
fscript | FontFamilyScript | ri | IndentRight
fswiss | FontFamilySwiss | row | Row
ftech | FontFamilyTechnical | rquote | ANSI Character 39
ftncn | NullDestination (Footnote cont.) | rtf | Rtf
ftnsep | NullDestination (Footnote separ) | rtlch | RightToLeftChars
ftnsepc | NullDestination (Footnote cont. separ) | rtldoc | RightToLeftDocument
green | ColorGreen | rtlmark | DisplayRightToLeft
header | NullDestination (Header) | rtlpar | RightToLeftParagraph
headerf | NullDestination (Header, first) | sec | TimeSecond
headerl | NullDestination (Header, left) | sect | EndSection
headerr | NullDestination (Header, right) | sectd | SectionDefault
horzdoc | HorizontalRender | strike | StrikeOut
hr | TimeHour | stylesheet | StyleSheet
I | Italic | sub | Subscript
info | DocumentArea (Info fields) | super | Superscript
intbl | InTable | tb | TabPosition
lang | Language | tc | NullDestination (Table of contents)
lchars | LeadingPunct | tx | TabPosition
ldblquote | ANSI Character 34 | ul | Underline
li | IndentLeft | uld | UnderlineDotted
line | SoftBreak | uldash | UnderlineDash
lquote | ANSI Character 39 | uldashd | UnderlineDashDotted
ltrch | LeftToRightChars | uldashdd | UnderlineDashDotDotted
ltrdoc | LeftToRightDocument | uldb | UnderlineDouble
ltrmark | DisplayLeftToRight | ulhair | UnderlineHairline
ltrpar | LeftToRightParagraph | ulnone | StopUnderline
mac | CharSetMacintosh | ulth | UnderlineThick
macpict | PictureQuickDraw | ulw | UnderlineWord
margl | MarginLeft | ulwave | UnderlineWave
marglsxn | SectionMarginLeft | up | Up
margr | MarginRight | v | HiddenText
margrsxn | SectionMarginRight | vertdoc | VerticalRender
min | TimeMinute | wbitmap | PictureWindowsBitmap
mo | TimeMonth | wbmbitspixel | BitmapBitsPerPixel
nocwrap | NoWordBreak | wbmplanes | BitmapNumPlanes
nooverflow | NoOverflow | wbmwidthbytes | BitmapWidthBytes
nosupersub | NoSuperSub | wmetafile | PictureWindowsMetafile
nowwrap | NoWordWrap | xe | NullDestination (index entry)
objautlink | ObjectAutoLink | yr | TimeYear
objclass | ObjectClass | zwj | ZeroWidthJoiner
objcropb | CropBottom | zwnj | ZeroWidthNonJoiner


RichTextBox Control Constants

Appearance Property

Constant | Value | Description
rtfFlat | 0 | Flat. Paints without visual effects.
rtfThreeD | 1 | (Default). 3D. Paints with three-dimensional effects.

Find Method

Constant | Value | Description
rtfWholeWord | 2 | Determines if a match is based on a whole word or a fragment of a word.
rtfMatchCase | 4 | Determines if a match is based on the case of the specified string as well as the text of the string.
rtfNoHighlight | 8 | Determines if a match appears highlighted in the RichTextBox control.

Loadfile, Savefile Methods

Constant | Value | Description
rtfRTF | 0 | (Default) RTF. The file loaded must be a valid .rtf file (LoadFile method) or the contents in the control are saved to an .rtf file (SaveFile method).
rtfText | 1 | Text. The RichTextBox control loads any text file (LoadFile method) or the contents in the control are saved to a text file (SaveFile method).

Mousepointer Property

Constant | Value | Description
rtfDefault | 0 | (Default) Shape determined by the object.
rtfArrow | 1 | Arrow.
rtfCross | 2 | Cross (cross-hair pointer).
rtfIbeam | 3 | I Beam.
rtfIcon | 4 | Icon (small square within a square).
rtfSize | 5 | Size (four-pointed arrow pointing north, south, east, and west).
rtfSizeNESW | 6 | Size NE SW (double arrow pointing northeast and southwest).
rtfSizeNS | 7 | Size N S (double arrow pointing north and south).
rtfSizeNWSE | 8 | Size NW, SE.
rtfSizeEW | 9 | Size E W (double arrow pointing east and west).
rtfUpArrow | 10 | Up Arrow.
rtfHourglass | 11 | Hourglass (wait).
rtfNoDrop | 12 | No Drop.
rtfArrowHourglass | 13 | Arrow and hourglass.
rtfArrowQuestion | 14 | Arrow and question mark.
rtfSizeAll | 15 | Size all.
rtfCustom | 99 | Custom icon specified by the MouseIcon property.

Selalignment Property

Constant | Value | Description
rtfLeft | 0 | (Default) Left. The paragraph is aligned along the left margin.
rtfRight | 1 | Right. The paragraph is aligned along the right margin.
rtfCenter | 2 | Center. The paragraph is centered between the left and right margins.

Scrollbars Property

Constant | Value | Description
rtfNone | 0 | (Default) None.
rtfHorizontal | 1 | Horizontal scroll bar only.
rtfVertical | 2 | Vertical scroll bar only.
rtfBoth | 3 | Both horizontal and vertical scroll bars.


SelChange Event (RichTextBox Control)

Occurs when the current selection of text in the RichTextBox control has changed or the insertion point has moved.

Syntax

Private Sub object_SelChange([index As Integer])

The SelChange event syntax has these parts:

Part | Description
object | An object expression that evaluates to an object in the Applies To list.
index | An integer that uniquely identifies a control if it's in a control array.

Remarks

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.


SelChange Event Example

This example checks the size of the current selection to see if the menu commands for cutting or copying text to the Clipboard should be enabled. To try this example, put a RichTextBox control and three Menu controls on a form to create a menu with commands to cut and copy. Paste this code into the SelChange event of the RichTextBox control. Then run the example.

Private Sub RichTextBox1_SelChange()
   If RichTextBox1.SelLength > 0 Then
      EditCutMenu.Enabled = True
      EditCopyMenu.Enabled = True
   Else
      EditCutMenu.Enabled = False
      EditCopyMenu.Enabled = False
   End If
End Sub


Error Messages (RichTextBox Control)

The following are the errors for the RichTextBox control, located in the RichTx32.OCX file:

Constant | Value | Description
rtfInvalidProcedureCall | 5 | Invalid procedure call.
rtfOutOfMemory | 7 | Out of memory.
rtfPathFileAccessError | 75 | The specified path/file name cannot be accessed or is invalid.
rtfInvalidFileFormat | 321 | Invalid file format.
rtfInvalidPropertyValue | 380 | Invalid property value.
rtfInvalidPropertyArrayIndex | 381 | Invalid property array index.
rtfSetNotSupported | 383 | Property is read-only.
rtfSetNotPermitted | 387 | Property cannot be set.
rtfGetNotSupported | 394 | Property is write-only.
rtfInvalidObjectUse | 425 | Invalid object use.
rtfWrongClipboardFormat | 461 | Specified format doesn't match format of data.
rtfDataObjectLocked | 672 | DataObject formats list may not be cleared or expanded outside of the OLEStartDrag event.
rtfExpectedAnArgument | 673 | Expected at least one argument.
rtfFormatNotByteArray | 674 | Non-intrinsic OLE drag and drop formats used with SetData require byte array data. GetData may return more bytes than were given to SetData.
rtfDataNotSetInFormat | 676 | Requested data was not supplied to the DataObject during the OLESetData event.
rtfInvalidCharPosition | 32000 | Invalid character position.
rtfInvalidHdc | 32001 | Invalid HDC.
rtfCannotLoadFile | 32002 | Unable to load specified file.
rtfInvalidKeyName | 32005 | Invalid or missing key name.
rtfInvalidClassName | 32006 | Invalid or missing OLE class name.
rtfKeyNotFound | 32007 | Key does not exist.
rtfOLESourceRquired | 32008 | Required source document or class name is missing.
rtfNonUniqueKey | 32009 | Key is not unique in collection.
rtfInvalidObject | 32010 | Invalid object.
rtfProtected | 32011 | The operation cannot be performed on protected text.
rtfOleCreate | 32012 | Unable to create object.
rtfOleServer | 32013 | Unable to start server application.


Add Method (OLEObjects Collection)

Adds an OLEObject object to an OLEObjects collection.

Syntax

object.Add index, key, sourcedoc, class

The Add Method syntax has these parts:

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
index | Optional. An integer that identifies a member of the object collection. If supplied, the new member will be inserted after the member specified by the index.
key | Optional. A unique string expression that can be used to access a member of the collection. The key and index arguments can be used interchangeably with the Item method of the collection to retrieve the OLEObject object.
sourcedoc | Required. The filename of a document used as a template for the embedded object. The RichTextBox control doesn't support linking, so the contents of the file will be copied into the OLEObject object. Must be a zero-length string ("") if you don't specify a source document.
class | Optional. The OLE class name for the object to be embedded. This argument is the ProgID used by OLE in the system registry. This argument is ignored if you specify a filename for sourcedoc.

Remarks

The following code adds a Microsoft Excel worksheet to the RichTextBox and sets its Key property to "SalesData":

RichTextBox1.OLEObjects.Add , "SalesData", , "Excel.Sheet.5"

When an object is added to the collection, it immediately becomes in-place active so the user can add data to it.


Add Method (OLEObjects Collection) Example

The following example presents a dialog box where you can find an OLEObject object (a bitmap) to add to a RichTextBox control. To try the example, place a CommonDialog and a RichTextBox control on a form, and paste the code into the Declarations section. Run the example and double-click on the control.

Private Sub RichTextBox1_DblClick()
   With CommonDialog1
      .Filter = ("bitmap (*.bmp)|*.bmp")
      .ShowOpen
   End With
   RichTextBox1.OLEObjects. _
   Add , , CommonDialog1.filename
End Sub


Find Method

Searches the text in a RichTextBox control for a given string.

Syntax

object.Find(string, start, end, options)

The Find method syntax has these parts:

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
string | Required. A string expression you want to find in the control.
start | Optional. An integer character index that determines where to begin the search. Each character in the control has an integer index that uniquely identifies it. The first character of text in the control has an index of 0.
end | Optional. An integer character index that determines where to end the search.
options | Optional. One or more constants used to specify optional features, as described in Settings.

Settings

The setting for options can include:

Constant | Value | Description
rtfWholeWord | 2 | Determines if a match is based on a whole word or a fragment of a word.
rtfMatchCase | 4 | Determines if a match is based on the case of the specified string as well as the text of the string.
rtfNoHighlight | 8 | Determines if a match appears highlighted in the RichTextBox control.

You can combine multiple options by using the Or operator.

Remarks

If the text searched for is found, the Find method highlights the specified text and returns the index of the first character highlighted. If the specified text is not found, the Find method returns –1.

If you use the Find method without the rtfNoHighlight option while the HideSelection property is True and the RichTextBox control does not have the focus, the control still highlights the found text. Subsequent uses of the Find method will search only for the highlighted text until the insertion point moves.

The search behavior of the Find method varies based on the combination of values specified for the start and end arguments. This table describes the possible behaviors:

Start | End | Search Behavior
Specified | Specified | Searches from the specified start location to the specified end location.
Specified | Omitted | Searches from the specified start location to the end of the text in the control.
Omitted | Specified | Searches from the current insertion point to the specified end location.
Omitted | Omitted | Searches the current selection if text is selected or the entire contents of the control if no text is selected.


Find Method Example

This example finds a string in a RichTextBox control based on a word entered in a TextBox control. After it finds the specified string, it displays a message box that shows the number of the line containing the specified word. To try this example, put a RichTextBox control, a CommandButton control and a TextBox control on a form. Load a file into the RichTextBox, and paste this code into the General Declarations section of the form. Then run the example, enter a word in the TextBox, and click the CommandButton.

Private Sub Command1_Click()
   Dim FoundPos As Integer
   Dim FoundLine As Integer
   ' Find the text specified in the TextBox control.
   FoundPos = RichTextBox1.Find(Text1.Text, , , rtfWholeWord)

   ' Show message based on whether the text was found or not.

   If FoundPos <> -1 Then
      ' Returns number of line containing found text.
      FoundLine = RichTextBox1.GetLineFromChar(FoundPos)
      MsgBox "Word found on line " & CStr(FoundLine)
   Else
      MsgBox "Word not found."
   End If
End Sub


GetLineFromChar Method

Returns the number of the line containing a specified character position in a RichTextBox control.

Syntax

object.GetLineFromChar(charpos)

The GetLineFromChar method syntax has these parts:

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
charpos | Required. A long integer that specifies the index of the character whose line you want to identify. The index of the first character in the RichTextBox control is 0.

Remarks

You use the GetLineFromChar method to find out which line in the text of a RichTextBox control contains a certain character position in the text. You might need to do this because the number of characters in each line of text can vary, making it very difficult to find out which line in the text contains a particular character, identified by its position in the text.


GetLineFromChar Method Example

This example finds a string in a RichTextBox control based on a word entered in a TextBox control. After it finds the specified string, it displays a message box that shows the number of the line containing the specified word. To try this example, put a RichTextBox control, a CommandButton control and a TextBox control on a form. Load a file into the RichTextBox, and paste this code into the General Declarations section of the form. Then run the example, enter a word in the TextBox, and click the CommandButton.

Private Sub Command1_Click()
   Dim FoundPos As Integer
   Dim FoundLine As Integer
   ' Find the text specified in the TextBox control.
   FoundPos = RichTextBox1.Find(Text1.Text, , , rtfWholeWord)

   ' Show message based on whether the text was found or not.

   If FoundPos <> -1 Then
      ' Returns number of line containing found text.
      FoundLine = RichTextBox1.GetLineFromChar(FoundPos)
      MsgBox "Word found on line " & CStr(FoundLine)
   Else
      MsgBox "Word not found."
   End If
End Sub


LoadFile Method

Loads an .rtf file or text file into a RichTextBox control.

Syntax

object.LoadFile pathname, filetype

The LoadFile method syntax has these parts:

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
pathname | Required. A string expression defining the path and filename of the file to load into the control.
filetype | Optional. An integer or constant that specifies the type of file loaded, as described in Settings.

Settings

The settings for filetype are:

Constant | Value | Description
rtfRTF | 0 | (Default) RTF. The file loaded must be a valid .rtf file.
rtfText | 1 | Text. The RichTextBox control loads any text file.

Remarks

When loading a file with the LoadFile method, the contents of the loaded file replaces the entire contents of the RichTextBox control. This will cause the values of the Text and RTFText properties to change.

You can also use the Input function in Visual Basic and the TextRTF and SelRTF properties of the RichTextBox control to read .rtf files. For example, you can load the contents of an .rtf file to the RichTextBox control as follows:

Open "mytext.rtf" For Input As 1

RichTextBox1.TextRTF = Strconv(InputB$(LOF(1), 1), vbUnicode)


LoadFile Method Example

This example displays a dialog box to choose an .rtf file, then loads that file into a RichTextBox control. To try this example, put a RichTextBox control, a CommandButton control, and a CommonDialog control on a form. Paste this code into the General Declarations section of the form. Then run the example.

Private Sub Command1_Click()
   CommonDialog1.Filter = "Rich Text Format files|*.rtf"
   CommonDialog1.ShowOpen
   RichTextBox1.LoadFile CommonDialog1.Filename, rtfRTF
End Sub


SaveFile Method

Saves the contents of a RichTextBox control to a file.

Syntax

object.SaveFile(pathname, filetype)

The SaveFile method syntax has these parts:

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
pathname | Required. A string expression defining the path and filename of the file to receive the contents of the control.
filetype | Optional. An integer or constant that specifies the type of file loaded, as described in Settings.

Settings

The settings for filetype are:

Constant | Value | Description
rtfRTF | 0 | (Default) RTF. The RichTextBox control saves its contents as an .rtf file.
rtfText | 1 | Text. The RichTextBox control saves its contents as a text file.

Remarks

You can also use the Write function in Visual Basic and the TextRTF and SelRTF properties of the RichTextBox control to write .rtf files. For example, you can save the highlighted contents of a RichTextBox control to an .rtf file as follows:

Open "mytext.rtf" For Output As 1

Print #1, RichTextBox1.SelRTF


SaveFile Method Example

This example displays a dialog box to choose an .rtf file to which you will save the contents of a RichTextBox control. To try this example, put a RichTextBox control, a CommandButton control, and a CommonDialog control on a form. Paste this code into the Click event of the CommandButton control. Then run the example.

Private Sub Command1_Click()
   CommonDialog1.ShowSave
   RichTextBox1.SaveFile CommonDialog1.Filename, rtfRTF
End Sub


SelPrint Method

Sends formatted text in a RichTextBox control to a device for printing.

Syntax

object.SelPrint(hdc)

The SelPrint method syntax has these parts:

Part | Description
object | An object expression that evaluates to an object in the Applies To list.
hdc | The device context of the device you plan to use to print the contents of the control.

Remarks

If text is selected in the RichTextBox control, the SelPrint method sends only the selected text to the target device. If no text is selected, the entire contents of the RichTextBox are sent to the target device.

The SelPrint method does not print text from the RichTextBox control. Rather, it sends a copy of formatted text to a device which can print the text. For example, you can send the text to the Printer object using code as follows:

RichTextBox1.SelPrint(Printer.hDC)

Notice that the hDC property of the Printer object is used to specify the device context argument of the SelPrint method.

Note If you use the Printer object as the destination of the text from the RichTextBox control, you must first initialize the device context of the Printer object by printing something like a zero-length string.


SelPrint Method Example

This example prints the formatted text in a RichTextBox control. To try this example, put a RichTextBox control, a CommonDialog control, and a CommandButton control on a form. Paste this code into the Click event of the CommandButton control. Then run the example.

Private Sub Command1_Click()
   CommonDialog1.Flags = cdlPDReturnDC + cdlPDNoPageNums
   If RichTextBox1.SelLength = 0 Then
      CommonDialog1.Flags = CommonDialog1.Flags + cdlPDAllPages
   Else
      CommonDialog1.Flags = CommonDialog1.Flags + cdlPDSelection
   End If
   CommonDialog1.ShowPrinter
   Printer.Print ""
   RichTextBox1.SelPrint CommonDialog1.hDC
End Sub


Span Method

Selects text in a RichTextBox control based on a set of specified characters.

Syntax

object.Span characterset, forward, negate

The Span method syntax has these parts:

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
characterset | Required. A string expression that specifies the set of characters to look for when extending the selection, based on the value of negate.
forward | Optional. A Boolean expression that determines which direction the insertion point moves, as described in Settings.
negate | Optional. A Boolean expression that determines whether the characters in characterset define the set of target characters or are excluded from the set of target characters, as described in Settings.

Settings

The settings for forward are:

Setting | Description
True | (Default) Selects text from the current insertion point or the beginning of the current selection forward, toward the end of the text.
False | Selects text from the current insertion point or the beginning of the current selection backward, toward the start of the text.

The settings for negate are:

Setting | Description
True | The characters included in the selection are those which do not appear in the characterset argument. The selection stops at the first character found that appears in the characterset argument.
False | (Default) The characters included in the selection are those which appear in the characterset argument. The selection stops at the first character found that does not appear in the characterset argument.

Remarks

The Span method is primarily used to easily select a word or sentence in the RichTextBox control.

If the Span method cannot find the specified characters based on the values of the arguments, then the current insertion point or selection remains unchanged.

The Span method does not return any data.


Span Method Example

This example defines a pair of keyboard shortcuts that selects text in a RichTextBox control to the end of a sentence (CTRL+S) or the end of a word (CTRL+W). To try this example, put a RichTextBox control on a form. Paste this code into the KeyUp event of the RichTextBox control. Then run the example.

Private Sub RichTextBox1_KeyUp (KeyCode As Integer, Shift As Integer)
   If Shift = vbCtrlMask Then
      Select Case KeyCode
         ' If Ctrl+S:
         Case vbKeyS
            ' Select to the end of the sentence.
            RichTextBox1.Span ".?!:", True, True
            ' Extend selection to include punctuation.
            RichTextBox1.SelLength = RichTextBox1.SelLength + 1
         ' If Ctrl+W:
         Case vbKeyW
            ' Select to the end of the word.
            RichTextBox1.Span " ,;:.?!", True, True
      End Select
   End If
End Sub


Upto Method

Moves the insertion point up to, but not including, the first character that is a member of the specified character set in a RichTextBox control.

Syntax

object.Upto(characterset, forward, negate)

The Upto method syntax has these parts:

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
characterset | Required. A string expression that specifies the set of characters to look for when moving the insertion point, based on the value of negate.
forward | Optional. A Boolean expression that determines which direction the insertion point moves, as described in Settings.
negate | Optional. A Boolean expression that determines whether the characters in characterset define the set of target characters or are excluded from the set of target characters, as described in Settings.

Settings

The settings for forward are:

Setting | Description
True | (Default) Moves the insertion point forward, toward the end of the text.
False | Moves the insertion point backward, toward the start of the text.

The settings for negate are:

Setting | Description
True | The characters not specified in the characterset argument are used to move the insertion point.
False | (Default) The characters specified in the characterset argument are used to move the insertion point.


Upto Method Example

This example defines a pair of keyboard shortcuts that moves the insertion point in a RichTextBox control to the end of a sentence (ALT+S) or the end of a word (ALT+W). To try this example, put a RichTextBox control on a form. Paste this code into the KeyUp event of the RichTextBox control. Then run the example.

Private Sub RichTextBox1_KeyUp (KeyCode As Integer, Shift As Integer)
   If Shift = vbAltMask Then
      Select Case KeyCode
         ' If Alt+S:
         Case vbKeyS
            ' Move insertion point to the end of the sentence.
               RichTextBox1.Upto ".?!:", True, False
         ' If Alt+W:
         Case vbkeyW
            ' Move insertion point to the end of the word.
               RichTextBox1.Upto " .?!:", True, False
      End Select
   End If
End Sub


OLEObject Object

An OLEObject object represents an insertable object within a RichTextBox control.

Remarks

The RichTextBox control enables you to add insertable objects to an RTF file. Insertable objects are represented by the OLEObject object.

Each embedded OLEObject object counts as one character in the RichTextbox control. That is, when counting from the beginning of the control, the object will take up one character position. OLE objects can be highlighted, cut or copied by the user, but they do not support any of the Selxxx properties (i.e. SelBold, SelItalic, etc.).

Each object supports a context menu that contains the standard Cut, Copy, Paste, and Delete commands, as well as Open and Edit. Open will cause the object’s application to be opened in its own window so that the object can be edited. Edit will cause the object to in-place activate if the object supports in-place activation.

You can manually add OLEObject 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.


AutoVerbMenu Property (RichTextBox Control)

Returns or sets a value that determines if a pop-up menu containing the selected object’s verbs is displayed when the user clicks the OLE object with the right mouse button.

Syntax

object.AutoVerbMenu [ = value ]

The AutoVerbMenu property has the following parts:

Part | Description
object | An object expression that evaluates to a RichTextBox control.
value | A Boolean expression that specifies whether a menu is displayed, as described in Settings.

Settings

The settings for value are:

Setting | Description
True | A pop-up menu is displayed when the user clicks the right mouse button on the object.
False | No pop-up menu is displayed.

Remarks

When this property is set to True, Click events and MouseDown events don't occur for the RichTextBox control when the OLE object is clicked with the right mouse button. Any other region of the control will generate the correct events.


Class Property (OLEObject Object)

Returns the class name of the embedded object.

Syntax

object.Class

The object argument is an object expression that evaluates to an object in the Applies To list.

Remarks

A class name defines the type of an object. Applications that support OLE or Automation fully qualify the class names of their objects using either of the following syntaxes:

application.objecttype.version
objecttype.version

The syntax for OLE class names has the following parts:

Part | Description
application | The name of the application that supplies the object.
objecttype | The object's name as defined in the object library.
version | The version number of the object or application that supplies the object.

For example, Microsoft Excel version 5.0 supports a number of objects, including worksheets and charts. Their class names are Excel.Sheet.5 and Excel.Chart.5. Microsoft WordArt version 2.0 supports a single object with the class name MSWordArt.2.

Note Some OLE programming documentation refers to the class name syntax as a programmatic ID (ProgID).

Creating an object by using the Add method of the OLEObjects collection, automatically sets the Class property of the OLEObject object.


DisableNoScroll Property

Returns or sets a value that determines whether scroll bars in the RichTextBox control are disabled.

Syntax

object.DisableNoScroll [= boolean]

The DisableNoScroll property syntax has these parts:

Part | Description
object | An object expression that evaluates to an object in the Applies To list.
Boolean | A Boolean expression specifying whether or not the scroll bars are enabled, as described in Settings.

Settings

The settings for boolean are:

Setting | Description
False | (Default) Scroll bars appear normally when displayed.
True | Scroll bars appear dimmed when displayed.

Remarks

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.


DisplayType Property (OLEObject Object)

Returns or sets a value indicating whether an object displays its contents or an icon.

Syntax

object.DisplayType [ = value]

The DisplayType property syntax has these parts:

Part | Description
object | An object expression that evaluates to an object in the Applies To list.
value | An integer or constant specifying whether an object displays its contents or an icon, as described in Settings.

Settings

The settings for value are:

Constant | Value | Description
rtfDisplayContent | 0 | Content. When the RichTextBox control contains an object, the object's data is displayed in the control.
rtfDisplayIcon | 1 | Icon. When the RichTextBox control contains an object, the object's icon is displayed in the control.

Remarks

After adding the object to the OLEObjects Collection, use the DisplayType property to change how that object is displayed.


DoVerb Method (OLEObject Object)

Opens an object for an operation, such as editing.

Syntax

object.DoVerb (verb)

The DoVerb method syntax has these parts:

Part | Description
object | An object expression that evaluates to an object in the Applies To list.
verb | Optional. The verb to execute of the OLEObject object within RichTextBox control. If not specified, the default verb is executed. The value of this argument can be one of the standard verbs supported by all objects or an index of the ObjectVerbs property array.

Remarks

The DoVerb method executes a verb of the specified OLEObject object. The verb argument is an index of one of the verbs listed in the ObjectVerbs property array or one of the standard verbs listed below.

Each object can support its own set of verbs. The following values represent standard verbs every object should support:

Constant | Value | Description
vbOLEPrimary | 0 | The default action for the object.
vbOLEShow | -1 | Activates the object for editing. If the application that created the object supports in-place activation, the object is activated within the RichTextBox control.
vbOLEOpen | -2 | Opens the object in a separate application window. If the application that created the object supports in-place activation, the object is activated in its own window.
vbOLEHide | -3 | For embedded objects, hides the application that created the object.
vbOLEUIActivate | -4 | If the object supports in-place activation, activates the object for in-place activation and shows any user interface tools. If the object doesn't support in-place activation, the object doesn't activate, and an error occurs.
vbOLEInPlaceActivate | -5 | If the user moves the focus to the embedded object, creates a window for the object and prepares the object to be edited. An error occurs if the object doesn't support activation on a single mouse click.
vbOLEDiscardUndoState | -6 | Used when the object is activated for editing to discard all record of changes that the object's application can undo.

Note These verbs may not be listed in the ObjectVerbs property array.


FileName Property (RichTextBox Control)

Returns or sets the filename of the file loaded into the RichTextBox control.

Syntax

object.FileName [= path]

The FileName property syntax has these parts:

Part | Description
object | Required. An object expression that evaluates to an object in the Applies To list.
path | String. The path of a valid file.

Settings

You can only specify the names of text files or valid .rtf files for this property.


MaxLength Property (RichTextBox Control)

Returns or sets a value indicating whether there is a maximum number of characters a RichTextBox control can hold and, if so, specifies the maximum number of characters.

Syntax

object.MaxLength [= long]

The MaxLength property syntax has these parts:

Part | Description
object | An object expression that evaluates to a RichTextBox control.
long | A long integer specifying the maximum number of characters a user can enter in the control. 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.

Remarks

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 Property

MultiLine Property (RichTextBox Control)

Returns or sets a value indicating whether a RichTextBox control can accept and display multiple lines of text. Read-only at run time.

Syntax

object.MultiLine

The object placeholder represents an object expression that evaluates to a RichTextBox control.

Settings

The MultiLine property settings are:

Setting | Description
True | Allows multiple lines of text.
False | (Default) Ignores carriage returns and restricts data to a single line.

Remarks

A multiple-line RichTextBox control wraps text as the user types text extending beyond the text box.

You can also add scroll bars to a larger RichTextBox control using the ScrollBars property. If no HScrollBar control (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.


BulletIndent Property

Returns or sets the amount of indent used in a RichTextBox control when SelBullet is set to True.

Syntax

object.BulletIndent [= integer]

The BulletIndent property syntax has these parts:

Part | Description
object | An object expression that evaluates to an object in the Applies To list.
integer | An integer that determines the amount of indent. These properties use the scale mode units of the Form object containing the RichTextBox control.

Remarks

The BulletIndent property returns Null if the selection spans multiple paragraphs with different margin settings.


ObjectVerbFlags Property (OLEObject Object)

Returns the menu state for each verb in the ObjectVerbs array.

Syntax

object.ObjectVerbFlags(value)

The ObjectVerbFlags property syntax has these parts:

Part | Description
object | An object expression that evaluates to an object in the Applies To list.
value | A numeric expression indicating the element in the array.

Return Values

The ObjectVerbFlags property returns the following values:

Constant | Value | Description
vbOLEFlagChecked | &H0008 | The menu item is checked.
vbOLEFlagDisabled | &H0002 | The menu item is disabled (but not dimmed).
vbOLEFlagEnabled | &H0000 | The menu item is enabled.
vbOLEFlagGrayed | &H0001 | The menu item is dimmed.
vbOLEFlagSeparator | &H0800 | The menu item is a separator bar.

Note These constants are listed in the Visual Basic (VB) object library in the Object Browser.

Remarks

The first verb in the ObjectVerbs array is the default verb. The remaining verbs in this array are suitable for displaying on a menu. The ObjectVerbFlags array contains information about the menu state (such as dimmed, checked, and so on) for each verb in the ObjectVerbs array.

When displaying a menu containing an object's verbs, check the value of this property to see how the item is displayed.


ObjectVerbsCount Property (OLEObject Object)

Returns the number of verbs supported by an object.

Syntax

object.ObjectVerbsCount

The object is an object expression that evaluates to an object in the Applies To list.

Remarks

Use this property to determine the number of elements in the ObjectVerbs property array.

The list of verbs an object supports may vary, depending on the state of the object.


ObjectVerbs Property (OLEObject Object)

Returns the list of verbs an object supports.

Syntax

object.ObjectVerbs(value)

The ObjectVerbs property syntax has these parts:

Part | Description
object | An object expression that evaluates to an object in the Applies To list.
value | A numeric expression indicating the element in the array.

Remarks

ObjectVerbs is a zero-based string array. Use this property along with the ObjectVerbsCount property to get the verbs supported by an object. These verbs are used to determine an action to perform when an object is activated with the DoVerb method. The list of verbs in the array varies from object to object and depends on the current conditions.

Each object can support its own set of verbs. The following values represent standard verbs supported by every object:

Constant | Value | Description
vbOLEPrimary | 0 | The default action for the object.
vbOLEShow | -1 | Activates the object for editing. If the application that created the object supports in-place activation, the object is activated within the RichTextBox control.
vbOLEOpen | -2 | Opens the object in a separate application window. If the application that created the object supports in-place activation, the object is activated in its own window.
vbOLEHide | -3 | For embedded objects, hides the application that created the object.
vbOLEUIActivate | -4 | If the object supports in-place activation, activates the object for in-place activation and shows any user interface tools. If the object doesn't support in-place activation, the object doesn't activate, and an error occurs.
vbOLEInPlaceActivate | -5 | If the user moves the focus to the embedded object, creates a window for the object and prepares the object to be edited. An error occurs if the object doesn't support activation on a single mouse click.
vbOLEDiscardUndoState | -6 | Used when the object is activated for editing to discard all record of changes that the object's application can undo.

Note These verbs may not be listed in the ObjectVerbs property array.

The first verb in the ObjectVerbs array, ObjectVerbs(0), is the default verb. Unless otherwise specified, this verb activates the object.

The remaining verbs in the array can be displayed on a menu. If it's appropriate to display the default verb in a menu, the default verb has two entries in the ObjectVerbs array.

Applications that display objects typically include an Object command on the Edit menu. When the user chooses Edit Object, a menu displays the object's verbs. Use the ObjectVerbs, ObjectVerbsCount, and ObjectVerbFlags properties to create such a menu at run time.

To automatically display the verbs in the ObjectVerbs array in a pop-up menu when the user clicks an object with the right mouse button, set the AutoVerbMenu property to True.


OLEObjects Property

Returns a reference to the OLEObjects collection.

Syntax

object.OLEObjects

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

The OLEObjects collection contains objects that can be inserted into the RichTextBox control, including text, bitmap, or other files.


Locked Property (RichTextBox Control)

Returns or sets a value indicating whether the contents in a RichTextBox control can be edited.

Syntax

object.Locked [= boolean]

The Locked property syntax has these parts:

Part | Description
object | An object expression that evaluates to a RichTextBox control.
boolean | A Boolean expression specifying whether the contents of the control can be edited, as described in Settings.

Settings

The settings for boolean are:

Setting | Description
True | You can scroll and highlight the text in the control, but you can't edit it. The program can still modify the text by changing the Text property.
False | (Default) You can edit the text in the control.


RightMargin Property

Returns or sets the right margin for the text in a RichTextBox control.

Syntax

object.RightMargin [ = value]

The RightMargin property syntax has these parts:

Part | Description
object | An object expression that evaluates to a RichTextBox control.
value | A numeric expression specifying the indent in twips from the right edge of the text to the right edge of the control, as described below.

Remarks

The RightMargin property is 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 When calculating a value for the RightMargin property, you must take in to account the width of the borders of the RichTextBox control if BorderStyle is set to rtfFixedSingle.


ScrollBars Property

ScrollBars Property (RichTextBox Control)

Returns or sets a value indicating whether a RichTextBox control has horizontal or vertical scroll bars. Read-only at run time.

Syntax

object.ScrollBars

The object placeholder represents an object expression that evaluates to a RichTextBox control.

Settings

The ScrollBars property settings are:

Constant | Value | Description
rtfNone | 0 | (Default) No scroll bars shown.
rtfHorizontal | 1 | Horizontal scroll bar only.
rtfVertical | 2 | Vertical scroll bar only.
rtfBoth | 3 | Both horizontal and vertical scroll bars shown.

Remarks

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 Microsoft Windows operating environment 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 Property

Returns or sets a value that controls the alignment of the paragraphs in a RichTextBox control. Not available at design time.

Syntax

object.SelAlignment [= value]

The SelAlignment property syntax has these parts:

Part | Description
object | An object expression that evaluates to an object in the Applies To list.
value | An integer or constant that determines paragraph alignment, as described in Settings.

Settings

The settings for value are:

Constant | Value | Description
 | Null | Neither. The current selection spans more than one paragraph with different alignments.
rtfLeft | 0 | (Default) Left. The paragraph is aligned along the left margin.
rtfRight | 1 | Right. The paragraph is aligned along the right margin.
rtfCenter | 2 | Center. The paragraph is centered between the left and right margins.

Remarks

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:

If IsNull(RichTextBox1.SelAlignment) = True Then
   ' Code to run when selection is mixed.
ElseIf RichTextBox1.SelAlignment = 0 Then
   ' Code to run when selection is left aligned.
...
End If


SelAlignment Property Example

This example uses an array of OptionButton controls to change the paragraph alignment of selected text in a RichTextBox control, but only if text is selected. The indices of the controls in the array correspond to settings for the SelAlignment property. To try this example, put a RichTextBox control and three OptionButton controls on a form. Give all three of the OptionButton controls the same name and set their Index property to 0, 1, and 2. Paste this code into the Click event of the OptionButton control. Then run the example.

Private Sub Option1_Click(Index As Integer)
   If RichTextBox1.SelLength > 0 Then
      RichTextBox1.SelAlignment = Index
   End If
End Sub


SelBold, SelItalic, SelStrikethru, SelUnderline Properties

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.

Syntax

object.SelBold [= value]

object.SelItalic [= value]

object.SelStrikethru [= value]

object.SelUnderline [= value]

The SelBold, SelItalic, SelStrikethru, and SelUnderline properties syntax has these parts:

Part | Description
object | An object expression that evaluates to an object in the Applies To list.
value | A Boolean expression or constant that determines the font style, as described in Settings.

Settings

The settings for value are:

Setting | Description
Null | Neither. 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.
False | (Default) None of the characters in the selection or character following the insertion point have the appropriate font style.

Remarks

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:

If IsNull(RichTextBox1.SelBold) = True Then
   ' Code to run when selection is mixed.
ElseIf RichTextBox1.SelBold = False Then
   ' Code to run when selection is not bold.
...
End If


SelCharOffset Property

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.

Syntax

object.SelCharOffset [= offset]

The SelCharOffset property syntax has these parts:

Part | Description
object | An object expression that evaluates to an object in the Applies To list.
offset | An integer that determines how far the characters in the current selection or that following the insertion point are offset from the baseline of the text, as described in Settings.

Settings

The settings for offset are:

Setting | Description
Null | Neither. The selection has a mix of characters with different offsets.
0 | (Default) Normal. The characters all appear on the normal text baseline.
Positive integer | Superscript. The characters appear above the baseline by the number of twips specified.
Negative integer | Subscript. The characters appear below the baseline by the number of twips specified.

Remarks

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:

If IsNull(RichTextBox1.SelCharOffset) = True Then
   ' Code to run when selection is mixed.
ElseIf RichTextBox1.SelCharOffset = 0 Then
   ' Code to run when selection is all on the baseline.
...
End If


SelCharOffset Property Example

This example uses a scroll bar to move selected text above or below the baseline. The minimum and maximum amount of offset is established by the font size of the text within the RichTextBox control. To try this example, put a RichTextBox control and a VScrollBar control on a form. Paste this code into the Change event of the VScrollBar control. Then run the example.

Private Sub VScroll1_Change ()
   VScroll1.Max = RichTextBox1.SelFontSize
   VScroll1.Min = -(VScroll1.Max)
   RichTextBox1.SelCharOffset = VScroll1.Value
End Sub


SelColor Property

Returns or sets a value that determines the color of text in the RichTextBox control. Not available at design time.

Syntax

object.SelColor [= color]

The SelColor property syntax has these parts:

Part | Description
object | An object expression that evaluates to an object in the Applies To list.
color | A value that specifies a color, as described in Settings.

Settings

The settings for color are:

Setting | Description
Null | The text contains a mixture of different color settings.
RGB colors | Colors specified in code with the RGB or QBColor functions.
System | Colors specified with the system color constants in the Visual Basic object library in the Object Browser. The color of the text then matches user selections for the specified constant in the Windows Control Panel.

Remarks

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.


SelColor Property Example

This example displays a color dialog box from a CommonDialog control to specify the color of selected text in a RichTextBox control. To try this example, put a RichTextBox control, a CommandButton control, and a CommonDialog control on a form. Paste this code into the Click event of the CommandButton control. Then run the example.

Private Sub Command1_Click()
   CommonDialog1.ShowColor
   RichTextBox1.SelColor = CommonDialog1.Color
End Sub


SelFontName Property

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.

Syntax

object.SelFontName [= string]

The SelFontName property syntax has these parts:

Part | Description
object | An object expression that evaluates to an object in the Applies To list.
string | A string expression that identifies a font installed on the system.

Remarks

The SelFontName property returns Null if the selected text contains different fonts.


SelFontName Property Example

This example displays a font dialog box from a CommonDialog control to specify font attributes of selected text in a RichTextBox control. To try this example, put a RichTextBox control, a CommandButton control, and a CommonDialog control on a form. Paste this code into the Click event of the CommandButton control. Then run the example.

Private Sub Command1_Click ()
   CommonDialog1.Flags = cdlCFBoth
   CommonDialog1.ShowFont
   With RichTextBox1
      .SelFontName = CommonDialog1.FontName
      .SelFontSize = CommonDialog1.FontSize
      .SelBold = CommonDialog1.FontBold
      .SelItalic = CommonDialog1.FontItalic
      .SelStrikethru = CommonDialog1.FontStrikethru
      .SelUnderline = CommonDialog1.FontUnderline
   End With
End Sub


SelFontSize Property

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.

Syntax

object.SelFontSize [= points]

The SelFontSize property syntax has these parts:

Part | Description
object | An object expression that evaluates to an object in the Applies To list.
points | An integer that specifies the size in points of the currently selected text or the characters immediately following the insertion point.

Remarks

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.


SelFontSize Property Example

This example displays a font dialog box from a CommonDialog control to specify font attributes of selected text in a RichTextBox control. To try this example, put a RichTextBox control, a CommandButton control, and a CommonDialog control on a form. Paste this code into the Click event of the CommandButton control. Then run the example.

Private Sub Command1_Click ()
   CommonDialog1.Flags = Both
   CommonDialog1.ShowFont
   With RichTextBox1
      .SelFontName = CommonDialog1.FontName
      .SelFontSize = CommonDialog1.FontSize
      .SelBold = CommonDialog1.FontBold
      .SelItalic = CommonDialog1.FontItalic
      .SelStrikethru = CommonDialog1.FontStrikethru
      .SelUnderline = CommonDialog1.FontUnderline
   End With
End Sub


SelHangingIndent, SelIndent, SelRightIndent Properties

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.

Syntax

object.SelHangingIndent [= integer]

object.SelIndent [= integer]

object.SelRightIndent [= integer]

The SelHangingIndent, SelIndent, and SelRightIndent properties syntax has these parts:

Part | Description
object | An object expression that evaluates to an object in the Applies To list.
integer | An integer that determines the amount of indent. These properties use the scale mode units of the Form object containing the RichTextBox control.

Remarks

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.


SelHangingIndent, SelIndent, SelRIghtIndent Properties Example

This example selects all the text in a RichTextBox control, then sets both the left and right indents to create margins. To try this example, put a RichTextBox control, a CommandButton control, and a TextBox control on a form. Load a file into the RichTextBox, and paste this code into the General Declarations section of the form. Then run the example.

Private Sub Command1_Click()
   Dim Margins As Integer
   Margins = CInt(Text1.Text)
   With RichTextBox1
      .SelStart = 1
      .SelLength = Len(RichTextBox1.Text)
      .SelIndent = Margins
      .SelRightIndent = Margins
   End With
End Sub


SelBullet Property

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.

Syntax

object.SelBullet [= value]

The SelBullet property syntax has these parts:

Part | Description
object | An object expression that evaluates to an object in the Applies To list.
Value | An integer or constant that determines the bullet style of the paragraph(s), as described in Settings.

Settings

The settings for value are:

Setting | Description
Null | Neither. 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.
False | (Default) The paragraphs in the selection don't have the bullet style.

Remarks

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:

If IsNull(RichTextBox1.SelBullet) = True Then
   ' Code to run when selection is mixed.
ElseIf RichTextBox1.SelBullet = False Then
   ' Code to run when selection doesn't have bullet style.
...
End If


SelBullet Property Example

This example changes the state of a CheckBox control on a form to show the bullet status of selected text in a RichTextBox control. To try this example, put a RichTextBox control and a CheckBox control on a form. Paste this code into the SelChange event of the RichTextBox control. Then run the example.

Private Sub RichTextBox1_SelChange()
   If IsNull(RichTextBox1.SelBullet) = True Then
      Check1.Value = vbGrayed
   ElseIf RichTextBox1.SelBullet = True Then
      Check1.Value = vbChecked
   ElseIf RichTextBox1.SelBullet = False Then
      Check1.Value = vbUnchecked
   End If
End Sub


SelProtected Property

Returns or sets a value which determines if the current selection is protected. Not available at design time.

Syntax

object.SelProtected [ = value ]

The SelProtected property syntax has the following parts:

Part | Description
object | An object expression that evaluates to a RichTextBox control.
value | A variant value that determines if the current selection is protected, as described in Settings.

Settings

Setting | Description
Null | The selection contains a mix of protected and non-protected characters.
True | All the characters in the selection are protected.
False | None of the characters in the selection are protected.

Remarks

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.


SelRTF Property

Returns or sets the text (in .rtf format) in the current selection of a RichTextBox control. Not available at design time.

Syntax

object.SelRTF [= string]

The SelRTF property syntax has these parts:

Part | Description
object | An object expression that evaluates to an object in the Applies To list.
string | A string expression in .rtf format.

Remarks

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.


SelRTF Property Example

This example saves the highlighted contents of a RichTextBox control to an .rtf file. To try this example, put a RichTextBox control and a CommandButton control on a form. Paste this code into the Click event of the CommandButton control. Then run the example.

Private Sub Command1_Click ()
   Open "mytext.rtf" For Output As 1
   Print #1, RichTextBox1.SelRTF
   Close 1

End Sub


SelTabCount, SelTabs Properties

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:

Part | Description
object | An object expression that evaluates to an object in the Applies To list.
count | An integer that determines the number of tab positions in the selected paragraph(s) or in those paragraph(s) following the insertion point.
index | An integer that identifies a specific tab. The first tab location has an index of zero (0). The last tab location has an index equal to SelTabCount minus 1.
location | An integer that specifies the location of the designated tab. The units used to express tab positions are determined by the scale mode of the Form object or other object containing the RichTextBox control.

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:

Private Sub RichTextBox1_GotFocus()
   ' Ignore errors for controls without the TabStop property.
   On Error Resume Next
   ' Switch off the change of focus when pressing TAB.
   For Each Control In Controls
      Control.TabStop = False
   Next Control
End Sub

Make sure to reset the TabStop property of the other controls when the RichTextBox control loses focus.


SelTabCount, SelTabs Properties Example

This example sets the number of tabs in a RichTextBox control to a total of five and then sets the positions of the tabs to multiples of five. To try this example, put a RichTextBox control and a CommandButton control on a form. Paste this code into the Click event of the CommandButton control. Then run the example.

Private Sub Command1_Click()
   With RichTextBox1
      .SelTabCount = 5
      For X = 0 To .SelTabCount - 1
         .SelTabs(X) = 5 * X
      Next X
   End With
End Sub


TextRTF Property

Returns or sets the text of a RichTextBox control, including all .rtf code.

Syntax

object.TextRTF [= string]

The TextRTF property syntax has these parts:

Part | Description
object | An object expression that evaluates to an object in the Applies To list.
string | A string expression in .rtf format.

Remarks

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.


TextRTF Property Example

This example saves the entire contents of a RichTextBox control to an .rtf file. To try this example, put a RichTextBox control and a CommandButton control on a form. Paste this code into the Click event of the CommandButton control. Then run the example.

Private Sub Command1_Click ()
   Open "mytext.rtf" For Output As 1
   Print #1, RichTextBox1.TextRTF
   Close 1

End Sub