Const LWA_COLORKEY = &H1
Const LWA_ALPHA = &H2
Const GWL_EXSTYLE = (-20)
Const WS_EX_LAYERED = &H80000
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 Sub Form_Load()
Dim Ret As Long
''Set the window style to ''Layered''
Ret = GetWindowLong(Me.hWnd, GWL_EXSTYLE)
Ret = Ret Or WS_EX_LAYERED
SetWindowLong Me.hWnd, GWL_EXSTYLE, Ret
''Set the opacity of the layered window to 128
''我们可以设置这个数值来控制透明程度
SetLayeredWindowAttributes Me.hWnd, 0, 128, LWA_ALPHA
End Sub
在VB.NET中,太简单了!系统为窗体提供了Opacity属性,来确定窗体的不透明和透明程度,0%为透明,100%为不透明。
以下程序通过循环显示窗体的透明度过程,为了让大家看清楚其变化,在循环过程中使用了System.Threading.Thread.Sleep来停顿。
Private Sub button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles button1.Click
''窗体的透明度渐变过程
button1.Enabled = False
Dim I As Double
For I = 0.01 To 1 Step 0.01
Me.Opacity = I
System.Windows.Forms.Application.DoEvents()
System.Threading.Thread.Sleep(5)
Next
Me.Opacity = 1
button1.Enabled = True
End Sub
4、使窗体右上角的X无效,禁止Alt+F4关闭窗体
在特殊窗体的应用中,我们有时需要把窗体右上角标题栏上的关闭按钮屏幕,当用户点击其它地方(比如说一个Button)退出,那我们怎么做呢?
我们还是来看一下在VB6中的实现,VB6中实现(借助API函数)
Private Declare Function GetSystemMenu Lib "user32" (ByVal hwnd As Long, ByVal bRevert As Long) As Long
Private Declare Function GetMenuItemCount Lib "user32" (ByVal hMenu As Long) As Long
Private Declare Function DrawMenuBar Lib "user32" (ByVal hwnd As Long) As Long
Private Declare Function RemoveMenu Lib "user32" (ByVal hMenu As Long, ByVal nPosition As Long, ByVal wFlags As Long) As Long
Const MF_BYPOSITION = &H400&
Const MF_REMOVE = &H1000&
Private Sub Form_Load()
Dim hSysMenu As Long, nCnt As Long
'' Get handle to our form''s system menu
'' (Restore, Maximize, Move, close etc.)
hSysMenu = GetSystemMenu(Me.hwnd, False)
If hSysMenu Then
'' Get System menu''s menu count
nCnt = GetMenuItemCount(hSysMenu)
If nCnt Then
'' Menu count is based on 0 (0, 1, 2, 3)
RemoveMenu hSysMenu, nCnt - 1, MF_BYPOSITION Or MF_REMOVE
RemoveMenu hSysMenu, nCnt - 2, MF_BYPOSITION Or MF_REMOVE '' Remove the seperator
DrawMenuBar(Me.hwnd)
'' Force caption bar''s refresh. Disabling X button
Me.Caption = "Try to close