Microsoft KB Archive/249341

= How To Create a Layered Window in Visual Basic =

Article ID: 249341

Article Last Modified on 6/29/2004

-

APPLIES TO


 * Microsoft Visual Basic 4.0 Professional Edition
 * Microsoft Visual Basic 5.0 Professional Edition
 * Microsoft Visual Basic 6.0 Professional Edition
 * Microsoft Visual Basic 4.0 Enterprise Edition
 * Microsoft Visual Basic 5.0 Enterprise Edition
 * Microsoft Visual Basic 6.0 Enterprise Edition

-



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.



Step-by-Step Example
 Create a new Standard EXE project in Visual Basic. Form1 is created by default.  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   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. 

