開啟 Visual Studio 2008,建立 Windows Forms Application 專案。在 Form1 上放置兩個 Timer 控件(Timer1、Timer2),並為視窗設定喜好的背景圖片。
利用 Timer1 將視窗向右下移動,移動到指定邊界後啟用 Timer2 向左上移動,形成來回漂浮效果。
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim pos As Point = New Point(100, 50) ' 初始位置
Me.DesktopLocation = pos
Timer1.Interval = 10
Timer1.Enabled = True
Timer2.Interval = 10
Timer2.Enabled = False
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Dim pos As Point = 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(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer2.Tick
Dim pos As Point = 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
執行程式後,視窗會在螢幕上不斷來回漂浮,展示基本的視窗位置控制與計時器交替運作技巧。