Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Visual Basic
Expertise: Beginner
Feb 7, 2003



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Make the Background of Your RichTextBox Controls Transparent

If you plan to require Windows 2000 for your application, you can make your standard VB RichTextBox control 100-percent transparent with a few simple API calls. To try this tip, create a new project (or use an existing one), add a RichTextBox control, and add this code and these declarations in a standard module:
Option Explicit

' Win32 APIs.
Private Declare Function GetWindowLong _
	Lib "user32" Alias "GetWindowLongA" _
	(ByVal hWnd As Long, _
	ByVal nIndex As Long) As Long
Private Declare Function SetWindowLong _
	Lib "user32" Alias "SetWindowLongA" _
	(ByVal hWnd As Long, ByVal nIndex As Long, _
	ByVal dwNewLong As Long) As Long
Private Declare Function SetWindowPos Lib "user32" _
	(ByVal hWnd As Long, ByVal hWndInsertAfter As _
	Long, ByVal X As Long, ByVal Y As Long, _
	ByVal cx As Long, ByVal cy As Long, _
	ByVal wFlags As Long) As Long
' Style bits.
Private Const GWL_EXSTYLE As Long = (-20)
Private Const WS_EX_TRANSPARENT As Long = &H20

' Force total redraw that shows new styles.
Private Const SWP_FRAMECHANGED = &H20
Private Const SWP_NOMOVE = &H2
Private Const SWP_NOZORDER = &H4
Private Const SWP_NOSIZE = &H1

Public Function Transparent(ByVal hWnd As Long, _
	Optional ByVal Value As Boolean = True) As _

	Dim nStyle As Long
	Const swpFlags As Long = _

	' Get current style bits.
	nStyle = GetWindowLong(hWnd, GWL_EXSTYLE)
	' Set new bits as desired.
	If Value Then
		nStyle = nStyle Or WS_EX_TRANSPARENT
		nStyle = nStyle And Not WS_EX_TRANSPARENT
	End If
	Call SetWindowLong(hWnd, GWL_EXSTYLE, nStyle)
	' Force redraw using new bits.
	SetWindowPos hWnd, 0, 0, 0, 0, 0, swpFlags
	' Make sure new style took.
	Transparent = _
		(GetWindowLong(hWnd, GWL_EXSTYLE) = nStyle)
End Function

You can use this function to toggle the transparency of your RichTextBox controls at will:

Private Sub Check1_Click()
	Call Transparent(RichTextBox1.hWnd, _
		(Check1.Value = vbChecked))
End Sub

To be on the safe side, check the OS version before making these calls, as the effects can be rather unpleasant in the wrong environment.

John Cullen
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date