Visual Studio 2008 作為經典的 .NET 開發環境,內建豐富的控制項庫,讓開發者能輕鬆建構功能強大的 Windows 應用程式。本文將示範兩項實用的表單特效技巧:浮動視窗與透明化視窗,適合 .NET 初學者快速上手,掌握表單動態行為的控制核心。
利用兩個 Timer 控制項協同運作,讓表單在螢幕上來回移動,形成「浮動」效果。
Form1 上拖曳 Timer1 與 Timer2。Public Class Form1
Inherits System.Windows.Forms.Form
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' 設定初始位置
Me.DesktopLocation = New Point(100, 50)
' Timer1:往右下移動
Timer1.Interval = 10
Timer1.Enabled = True
' Timer2:往左上移動,初始停用
Timer2.Interval = 10
Timer2.Enabled = False
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Dim pos As New Point(Me.DesktopLocation.X + 2, Me.DesktopLocation.Y + 1)
If pos.X < 600 Or pos.Y < 400 Then
Me.DesktopLocation = pos
Else
Timer1.Enabled = False
Timer2.Enabled = True
End If
End Sub
Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
Dim pos As New Point(Me.DesktopLocation.X - 2, Me.DesktopLocation.Y - 1)
If pos.X > 100 Or pos.Y > 50 Then
Me.DesktopLocation = pos
Else
Timer1.Enabled = True
Timer2.Enabled = False
End If
End Sub
End Class
運作原理:Timer1 推動表單向右下方移動,超過邊界 (600, 400) 時切換至 Timer2,後者將表單拉回左上方 (100, 50),形成無限循環。執行專案即可看到表單在螢幕上「游走」。
結合 TrackBar(軌跡條)、Label 與 Timer,實現手動調整透明度與自動淡入淡出動畫。
Label1、TrackBar1、Timer1 至表單。TrackBar1:Minimum=0、Maximum=100、TickFrequency=10、Value=100Label1.Text = "選擇視窗透明度:"Timer1.Interval = 100Public Class Form1
Inherits System.Windows.Forms.Form
Dim tps As Integer = 100 ' 透明度暫存值 (0-100)
Dim bol As Boolean = False ' 方向旗標:False=淡入, True=淡出
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Timer1.Enabled = True ' 啟動自動淡入淡出
End Sub
' 手動拖曳軌跡條調整透明度
Private Sub TrackBar1_Scroll(sender As Object, e As EventArgs) Handles TrackBar1.Scroll
Me.Opacity = TrackBar1.Value / 100
Label1.Text = "視窗透明度:" & CStr(Me.Opacity * 100) & "%"
End Sub
' 自動淡入淡出動畫邏輯
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
If Not bol Then ' 淡入階段
tps += 1
Me.Opacity = tps / 100
If Me.Opacity >= 1 Then
Timer1.Enabled = False
bol = True
End If
Else ' 淡出階段
tps -= 1
Me.Opacity = tps / 100
If Me.Opacity <= 0 Then
Timer1.Enabled = False
bol = False
End If
End If
End Sub
' 關閉視窗前確認,並重置狀態
Private Sub Form1_Closing(sender As Object, e As ComponentModel.CancelEventArgs) Handles MyBase.Closing
Timer1.Enabled = True
If MsgBox("確定要關閉視窗嗎?", MsgBoxStyle.OkCancel) = MsgBoxResult.Ok Then
e.Cancel = False
Else
Timer1.Enabled = False
Me.Opacity = 1
tps = 100
bol = True
e.Cancel = True
End If
End Sub
End Class
效果說明:拖曳軌跡條可即時改變 Opacity 屬性(0~1),實現從完全可見到完全隱形的過渡;Timer 則提供自動呼吸燈般的淡入淡出動畫,極具視覺張力。
透過 DesktopLocation 控制位置與 Opacity 控制透明度,配合 Timer 實現動態行為,僅用幾行核心程式碼即可打造出炫酷的表單特效。這兩個範例展示了 VB.NET 操作視窗屬性的直觀與強大,是進階 UI 開發的絕佳入門實作。