#t#VB.NET还是比较常用的,于是我研究了一下VB.NET窗体透明度渐变效果:我们还是来看一下在VB6中的实现,在这里拿出来和大家分享一下,希望对大家有用。
使用这个函数,可以轻松控制VB.NET窗体透明度。按照微软的要求,透明窗体在创建时应使用WS_EX_LAYERED参数(用CreateWindowEx),或者在创建后设置该参数(用SetWindowLong),我选用后者。
SetLayeredWindowAttributes函数,其中hwnd是透明窗体的句柄,crKey为颜色值,bAlpha是透明度,取值范围是[0,255],dwFlags是透明方式,可以取两个值:当取值为 LWA_ALPHA时,crKey参数无效,bAlpha参数有效;当取值为LWA_COLORKEY时,bAlpha参数有效而窗体中的所有颜色为 crKey的地方将变为透明。
- Const LWA_COLORKEY = &H1
- Const LWA_ALPHA = &H2
- Const GWL_EXSTYLE = (-20)
- Const WS_EX_LAYERED = &H80000
- PrivateDeclareFunction GetWindowLong Lib "user32" Alias "GetWindowLongA"
(ByVal hWnd AsLong, ByVal nIndex AsLong) AsLong- PrivateDeclareFunction SetWindowLong Lib "user32" Alias "SetWindowLongA"
(ByVal hWnd AsLong, ByVal nIndex AsLong, ByVal dwNewLong AsLong) AsLong- PrivateDeclareFunction SetLayeredWindowAttributes Lib "user32"
(ByVal hWnd AsLong, ByVal crKey AsLong, ByVal bAlpha AsByte, ByVal dwFlags AsLong) AsLong- PrivateSub Form_Load()
- Dim Ret AsLong
- 'Set the window style to 'Layered'
- Ret = GetWindowLong(Me.hWnd, GWL_EXSTYLE)
- RetRet = 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
- EndSub
在VB.NET中,太简单了!系统为窗体提供了Opacity属性,来确定窗体的不透明和透明程度,0%为透明,100%为不透明。以下程序通过循环显示VB.NET窗体透明度过程,为了让大家看清楚其变化,在循环过程中使用了System.Threading.Thread.Sleep来停顿。
- PrivateSub button1_Click(ByVal sender As System.Object,
_ByVal e As System.EventArgs) Handles button1.Click- '窗体的透明度渐变过程
- button1.Enabled = False
- Dim I AsDouble
- 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
- EndSub