RichTextBox Control - Crowley
RichTextBox Control - Crowley
Introduction
The RichTextBox is a additional VB component that comes with Visual Basic Professional and Enterprise Edition.
This control allows your program to create formatted text (i.e. bulleted, bold and coloured text) in RTF (Rich Text
Format). This file format can then be read by other programs like WordPad and MS Word. It could be use in two main
ways.
1) You could program your application like a Word Processor, which would give your user much more freedom than
just plain text
2) Use the control in an application where it would be beneficial to the user if you colour certain portions of text. E.G in
a HTML editor, where it makes tags one colour, and text another.
To add the Rich Text Box control to your project click Project|Components. Check the box next to Microsoft Rich
TextBox Control. Click OK
REQUIRED FILES
If you will be installing a program using the RichTextBox control, you need to distribute the following files:
RichTx32.ocx - 200KB
RichEd32.dll - 171KB
Where format is either the constant rtfRTF (Rich Text Format) or rtfText (Plain Text).
So
This saves the current file in RTF. RichTextBox1.Filename stores the current files path.
Formatting text
To make selected text bold, underlined, italic or strikethrough you can use the following code:
Statement Action
RichTextBox1.SelAlignment = Alignment
Constant Alignment
vbRight Right
vbLeft Left
vbCenter Centre
So, the following code will set make the selected text underlined, and aligned to the right.
RichTextBox1.SelAlignment = vbRight
RichTextBox1.SelUnderline = True
If you want to know how to make a toolbar that shows the current underlined/italic/etc state, click here.
Advanced Formatting
Apart from making text bold, underlined, italic or strikethrough you can also use bullets, tab stops and left and right
indents. Of these, tab stops are the most complicated and will be covered in another section. Note: For any of these
examples, set the Scale Mode property on the Form that the text box is contained to Millimetres, or adjust the values
shown in any examples on this page.
Statement Action
RichTextBox1.BulletIndent = 10 Sets the distance between the bullet and the text to 10 (applies to all)
RichTextBox1.RightMargin = 100 Sets the right margin of all the text in the Rich Text Box to 100.
RichTextBox1.SelRightIndent = 100 Sets the right indent of all the selected text in the Rich Text Box to 100 (measured from the
left).
So, the following code will set make the selected text bulleted, indents by 10 mm and sets the right margin to 100 mm
Tab Stops
Tab Stops allow you to specify the intervals the cursor moves to when you press the tab key. (Try right clicking on the
ruler in word to see an example). The Rich Text Box supports this, but you must note that in order for it to work, the tab
values have to be in order. For this I use a list box. The current tabs are loaded into the list box, and can be removed
or added and when the dialog is closed, the contents of the list box loaded back into the SelTabs property. Note that
the property name is SelTabs, ie that they are not applied to the whole document.
Create a form called frmMain with a rich text box on it called txtText. Then create a form named frmTabStops, and add
the following controls:
End Sub
' OK code
Public Sub cmdOK_Click()
' Update sel tabs
frmMain.txtText.SelTabCount = cboTabs.ListCount
For i = 0 To cboTabs.ListCount - 1
' Add the sel tab
frmMain.txtText.SelTabs(i) = cboTabs.List(i)
Next
Unload Me
End Sub
Printing
It is very easy to print from the RichTextbox. Use the following statement:
fMainForm.ActiveForm.txtText.SelPrint (Printer.hDC)
However, it will send the text to the printer without any margins, so the text will be printed right on the edge of the
sheet. However, it is possible to do this, just with much more code! Click here for more info.
FindString is the Text to fine. StartPos is an integer representing the start position. To start from the beginning of the
document this would be set to 0. EndPos is an integer representing the end position. If this is left blank then it is set
the the length of the document. Options contains one or more of the following flags:
Flag Action
The following code searches RichTextBox1 for the Text contained in Text1. It searched for the whole word only:
Sub Command1_Click()
SearchText = Text1.Text
gOptions = rtfWholeWord
Result = RichTextBox1.Find (SearchText,0, ,gOptions)
If Result = -1 Then
Msgbox "Text not found"
Else
Msgbox "Text Found"
End If
End Sub
Once you have found the text, you can change it using the SelText property. The following code will search the whole of
RTB1 for the text contained in txtFind, and then will replace that text with the text in txtReplace. It uses Match Case and
Whole Word Only.
Bitmap (*.bmp)
Gif (*.gif)
JPEG (*.jpg)
It also supports
The following code shows a dialog to select a file, and then inserts the file into the RichTextBox
Sub Command1_Click()
With CommonDialog1
.CancelError = True
.Filter = "All Files *.*|*.*"
On Error Resume Next
' Show open dialog
.ShowOpen
If Err Then Exit Sub
End With
On Error Resume Next
' Attemt to add OLE Object
RichTextBox1.OLEObjects.Add , , CommonDialog1.Filename
' Check to see if an error has occured
If Err = 462 Then
MsgBox "Error importing file, may be low on memory"
End If
End Sub
Advanced Features
The next few sections discuss more advanced (and hidden!) features of the RichTextBox.
To change the WYSIWYG settings (such as page orientation and paper size), simply change the printer properties,
and call SetViewMode again. This will then allow for pages to be set to landscape, or an A5 page. Add this code to a
module
Multiple undo/redo
The RichTextBox actually supports multiple undo and redo. However, this functionality is hidden from VB
programmers. In order to be able to use the undo and redo facilities, you need to add the following code.
Add this code to the Form_Load() event of the form that contains the RichTextBox control. We are calling the
RichTextBox rtfText
mnuEdit &Edit
mnuEditUndo &Undo
mnuEditRedo &Redo
mnuEditCut Cu&t
mnuEditCopy &Copy
mnuEditPaste &Paste
mnuEditClear C&lear
Call the UpdateItems procedure in the mnuEdit_Click() event. This procedure updates the menu items.
'///////////////////////////////////////////////////////
'// Methods
Public Sub Undo()
SendMessageLong rtfText.hWnd, EM_UNDO, 0, 0
End Sub
Public Sub Redo()
SendMessageLong rtfText.hWnd, EM_REDO, 0, 0
End Sub
Public Sub Cut()
SendMessageLong rtfText.hWnd, WM_CUT, 0, 0
End Sub
Public Sub Copy()
SendMessageLong rtfText.hWnd, WM_COPY, 0, 0
End Sub
Public Sub Paste()
SendMessageLong rtfText.hWnd, WM_PASTE, 0, 0
End Sub
Public Sub Clear()
rtfText.SelText = Empty
End Sub
Public Sub UpdateItems()
Dim bCanUndo As Boolean
'// Undo/Redo options:
bCanUndo = CanUndo
mnuEditUndo.Enabled = bCanUndo
'// Set Undo Text
If (bCanUndo) Then
mnuEditUndo.Caption = "&Undo " & TranslateUndoType(UndoType)
Else
mnuEditUndo.Caption = "&Undo"
End If
'// Set Redo Text
bCanUndo = CanRedo
If (bCanUndo) Then
mnuEditRedo.Caption = "&Redo " & TranslateUndoType(RedoType)
Else
mnuEditRedo.Caption = "&Redo"
End If
mnuEditRedo.Enabled = bCanUndo
tbToolBar.Buttons("Redo").Enabled = bCanUndo
'// Cut/Copy/Paste/Clear options
mnuEditCut.Enabled = CanCopy
mnuEditCopy.Enabled = CanCopy
mnuEditPaste.Enabled = CanPaste
mnuEditClear.Enabled = CanCopy
End Sub
'// Returns the undo/redo type
Private Function TranslateUndoType(ByVal eType As ERECUndoTypeConstants) As String
Select Case eType
Case ercUID_UNKNOWN
TranslateUndoType = "Last Action"
Case ercUID_TYPING
TranslateUndoType = "Typing"
Case ercUID_PASTE
TranslateUndoType = "Paste"
Case ercUID_DRAGDROP
TranslateUndoType = "Drag Drop"
Case ercUID_DELETE
TranslateUndoType = "Delete"
Case ercUID_CUT
TranslateUndoType = "Cut"
End Select
End Function
Public Declare Function SendMessageLong Lib "user32" Alias "SendMessageA" (ByVal hwnd As
Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
Public Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long,
ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As Any) As Long
And that's it! What you thought is impossible, is actually possible in a few lines of code. Of course, it would have been
much easier if Microsoft had provided these functions for VB programmers anyway. This code has been adapted from
VB Accelerator's RichEdit control.
'///////////////////////////////////////////////////////
'// Subclassing
'// Required for automatic url detection
'///////////////////////////////////////////////////////
Case WM_NOTIFY
CopyMemory tNMH, ByVal lParam, Len(tNMH)
If (tNMH.hwndFrom = rtfText.hwnd) Then
Select Case tNMH.code
Case EN_LINK
CopyMemory tEN, ByVal lParam, Len(tEN)
LinkOver tEN.msg, tEN.chrg.cpMin, tEN.chrg.cpMax - tEN.chrg.cpMin
End Select
End If
End Select
End Function
Private Property Let ISubclass_MsgResponse(ByVal RHS As SSubTimer.EMsgResponse)
'// this sub has to exist whether you like it or not
End Property
Private Property Get ISubclass_MsgResponse() As SSubTimer.EMsgResponse
ISubclass_MsgResponse = emrPostProcess
End Property
'///////////////////////////////////////////////////////
'// URL detection
Public Property Let AutoURLDetect(ByVal bState As Boolean)
m_bAutoURLDetect = bState
SendMessageLong rtfText.hwnd, EM_AUTOURLDETECT, Abs(bState), 0
End Property
Public Property Get AutoURLDetect() As Boolean
AutoURLDetect = m_bAutoURLDetect
End Property
Public Declare Function SendMessageLong Lib "user32" Alias "SendMessageA" (ByVal hwnd As
Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
Public Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long,
ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As Any) As Long
Public Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" (ByVal hwnd As
Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String,
ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long
That's it! This code has been adapted from VB Accelerator's RichEdit control.
Related tags
visual basic
Languages Web Development Frameworks & Architecture Other major sections
C# Programming ASP.NET (Quickstart) .NET Framework .NET Forum
VB.NET PHP Java Developer Jobs
Java JavaScript Patterns Podcasts
C++ CSS Test Driven Development Software books