How To Create a Layered Window in Visual Basic (249341)



The information in this article applies to:

  • Microsoft Visual Basic Professional Edition for Windows 4.0
  • Microsoft Visual Basic Professional Edition for Windows 5.0
  • Microsoft Visual Basic Professional Edition for Windows 6.0
  • Microsoft Visual Basic Enterprise Edition for Windows 4.0
  • Microsoft Visual Basic Enterprise Edition for Windows 5.0
  • Microsoft Visual Basic Enterprise Edition for Windows 6.0

This article was previously published under Q249341

SUMMARY

Microsoft Windows 2000 has the ability to create translucent windows. These windows are called layered windows. This article describes how to create a layered window by using Visual Basic.

MORE INFORMATION

Step-by-Step Example

  1. Create a new Standard EXE project in Visual Basic. Form1 is created by default.
  2. Add the following code to the General Declarations section of Form1:
    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 SetLayeredWindowAttributes Lib "user32" _
      (ByVal hwnd As Long, ByVal crKey As Long, ByVal bAlpha As Byte, _
      ByVal dwFlags As Long) As Long
    
    Private Const GWL_EXSTYLE = (-20)
    Private Const WS_EX_LAYERED = &H80000
    Private Const WS_EX_TRANSPARENT = &H20&
    Private Const LWA_ALPHA = &H2&
    
    Option Explicit
    
    Private Sub Form_Load()
        Dim lOldStyle As Long
        Dim bTrans As Byte ' The level of transparency (0 - 255)
    
        bTrans = 128
        lOldStyle = GetWindowLong(Me.hWnd, GWL_EXSTYLE)
        SetWindowLong Me.hWnd, GWL_EXSTYLE, lOldStyle Or WS_EX_LAYERED
        SetLayeredWindowAttributes Me.hWnd, 0, bTrans, LWA_ALPHA
    End Sub
    					
  3. Run the example program by pressing the F5 key. The form should look like a normal Visual Basic window. However, windows that are lower in the Z order should be partially visible through the window. It is also possible to make mouse events go through to the lower windows by changing the preceding code line
    SetWindowLong Me.hwnd, GWL_EXSTYLE, lOldStyle Or WS_EX_LAYERED
    to:
    SetWindowLong Me.hwnd, GWL_EXSTYLE, lOldStyle Or WS_EX_LAYERED Or WS_EX_TRANSPARENT
    However, the form does not remain topmost if another form is activated. See the "Reference" section for information on how to create a form that remains on top.

REFERENCES

For additional information how to create a topmost window, click the article number below to view the article in the Microsoft Knowledge Base:

184297 How To Create a Form That Always Stays on Top


Modification Type:MinorLast Reviewed:6/29/2004
Keywords:kbAPI kbForms kbhowto KB249341 kbAudDeveloper