Creating Partially Translucent/Transparent Windows in VB (2)

CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Introduction

In Part 1, we talked about translucent/transparent windows and we mentioned ‘holes’ and color. We will see how to make holes in a window in this part.

The steps are the same as in translucency (see Part 1). The only difference is in the parameters to the SetLayeredWindowAttributes function.

As we said, SetLayeredWindowAttributes is responsible for translucency. It can also make ‘holes’ in a window.

Public Declare Function SetLayeredWindowAttributes Lib "user32" _
   (ByVal hwnd As Long, ByVal color As Long, ByVal bAlpha As Byte, _
    ByVal alpha As Long) As Boolean

hwnd: Handle to layered window. ex Me.hwnd.

color: Color used to make areas of a window completely transparent.

bAlpha: Value between 0 (transparent) and 255 (opaque) for alpha blend function.

Flag: Value between 1 and 3. 1 for color, 2 for alpha, and 3 for both of them together.

Example:

SetLayeredWindowAttributes Me.hwnd, RGB(0, 255, 0), 0, 1

Setting color to a value, and setting flag to 1 will cause anything having our color value to become a ‘hole.’

So, if we set color to RGB(0,255,0) and then we put a control with color value RGB(0, 255, 0), the portion of the window that the control occupies will become a ‘hole’ and we can see whatever’s behind it.

Let’s try it.

I will use a slightly modified version of the SetTranslucent function from Part 1. I’m going to add two parameters to it: Color and Flag. Here’s the new SetTranslucent function:

Sub SetTranslucent(ThehWnd As Long, color As Long, nTrans _
                   As Integer, flag As Byte)
On Error GoTo ErrorRtn

   'SetWindowLong and SetLayeredWindowAttributes are API functions;
   'see MSDN for details
   Dim attrib As Long
   attrib = GetWindowLong(ThehWnd, GWL_EXSTYLE)
   SetWindowLong ThehWnd, GWL_EXSTYLE, attrib Or WS_EX_LAYERED
   'anything with color value color will completely disappear if
   'flag = 1 or flag = 3
      SetLayeredWindowAttributes ThehWnd, color, nTrans, flag
   Exit Sub
ErrorRtn:
MsgBox Err.Description & " Source : " & Err.Source

End Sub

That’s all there is to it.

Download the project, source, and executable all in one ZIP file.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read