Note: This page was imported from a much older version of my site. The contents are still relevant but haven’t been changed in many 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
GetRGB() function does the reverse of the built in
RGB() function, returning R, G, B values from an
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.
Assuming there is a RichTextbox control called
RichTextBox with a selection set, the following code demonstrates how to call the functions.