Introduction
This article provides the code required to implement control transparency in VB 2008.
Background
The transparency option in VB 2008 is not as useful as it could be because the Transparency
setting causes the application to hide all of the graphics under the control, all the way through to the form background.
Using the code
The code provided below can be copied directly into your project. It works by using the “CopyFromScreen
” method of the Graphics
object to copy a snapshot of the screen area directly behind the given control into a bitmap. This bitmap is then assigned as the BackImage
of the control.
Public Sub SetBackgroundTransparent(ByRef theCtl As Control)
Dim intSourceX As Integer
Dim intSourceY As Integer
Dim intBorderWidth As Integer
Dim intTitleHeight As Integer
Dim bmp As Bitmap
Dim MyGraphics As Graphics
intBorderWidth = (Me.Width - Me.ClientRectangle.Width) / 2
intTitleHeight = ((Me.Height - (2 * intBorderWidth)) - _
Me.ClientRectangle.Height)
intSourceX = Me.Left + intBorderWidth + theCtl.Left
intSourceY = Me.Top + intTitleHeight + intBorderWidth + theCtl.Top
theCtl.Visible = False
Application.DoEvents()
bmp = New Bitmap(theCtl.Width, theCtl.Height)
MyGraphics = Graphics.FromImage(bmp)
MyGraphics.CopyFromScreen(intSourceX, intSourceY, 0, 0, bmp.Size)
MyGraphics.Dispose()
theCtl.BackgroundImageLayout = ImageLayout.None
theCtl.BackgroundImage = bmp
theCtl.Visible = True
Application.DoEvents()
End Sub