RichTextBox Background Colours
The RichTextbox control that comes with VB is actually a “wrapper” for 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.
If this code is to be used on Windows 95 or 98 the version of the RichEdit control will need updating. Microsoft provide a redistribution file that can be used for this, available below.
Usage:
' Assuming there is a RichTextbox control called "RichTextBox" with a selection set Call SetSelBackColor(RichTextBox.hwnd, vbCyan) ' Would set the selected text to have a background colour of cyan Call SetSelBackColor(RichTextBox.hwnd, RGB(0, 0, 0)) ' Would set the selected text to have a background colour of the RGB value ' 0,0,0, which is black Call SetSelBackColor(RichTextBox.hwnd, -1) ' This "resets" the background colour for the selected region, as if no ' colour had been applied MsgBox GetSelBackColor(RichTextBox.hwnd) ' Will return the OLE_COLOR of the current back colour
Screenshots
Download
The files available for this release are below.
| File | Description |
|---|---|
| modRTBAPI.bas | VB Module - The .bas module file containing the function. |
| RichTextboxHighlight.zip | Example project - A zipfile containing a sample project using the above code, and a compiled demo exe. |
| Riched30.exe | RichEdit 3 installer - The installer from Microsoft for Richedit 3, this is only needed on Windows 95 or 98. |
