VB6 RichTextBox control

This page was imported from a much older version of my site. The contents are still relevant but haven't been changed in over five years.

The RichTextbox control that comes with VB is actually a “wrapper” for the real RichEdit and lacks alot of the functionality of the real thing. Whereas it comes with a .SelColor method one feature it lacks is a .SelBackColor method, which would enable the background colour to be changed. This is similar to the highlight feature in Microsoft Word and is shown in the screenshots below.

This solution isn’t perfect but it does the job. Two functions are used to either set or get the current back colour for the selected text. To use it, simply pass the hwnd (window handle) of a RichTextbox control and the new colour.

Note that the colour is defined as an OLE_COLOR and should therefore be a long value representing the colour. The built in VB function RGB() will return the necessary long value given the RGB components of a colour. The VB colour constants can also be used, such as vbBlack or vbRed.

The GetRGB() function does the reverse of the built in RGB() function, returning R, G, B values from an OLE_COLOR.

If SetSelBackColor is called and the RichTextbox currently has no selection (.SelLength=0), any text typed afterwards from the current caret point will inherit the new back colour. If GetSelBackColor is called and there is no selection, the back colour of the character under the caret is returned.

Usage

Assuming there is a RichTextbox control called "RichTextBox" with a selection set, the following code demonstrates how to call the functions.

1
2
3
4
5
6
7
8
9
10
11
12
13
' Would set the selected text to have a background colour of cyan
Call SetSelBackColor(RichTextBox.hwnd, vbCyan)

' Would set the selected text to have a background colour of the RGB value
' 0,0,0, which is black
Call SetSelBackColor(RichTextBox.hwnd, RGB(0, 0, 0))

' This "resets" the background colour for the selected region, as if no
' colour had been applied
Call SetSelBackColor(RichTextBox.hwnd, -1)

' Will return the OLE_COLOR of the current back colour
MsgBox GetSelBackColor(RichTextBox.hwnd)

Screenshot

Example of the RichTextBox highlighting code

Download

Download the module - The code only
Download a sample project - Shows how to use the code

4 comments on “VB6 RichTextBox control
  1. livetogogo says:

    hi. thanks. very very good. I will use the my project.

  2. Charlie Howard says:

    Thank you, it works very well, even with VB5. Nice to know that people still support the old VB's even if Microsoft won't.

  3. david says:

    still working in 2015 with VB6 on Windows 8.1
    Still love this program, thanks again.

  4. taufik says:

    thanks for sharing.

Leave a Reply

Your email address will not be published. Required fields are marked *

*