下面是一個使用VB編寫的簡單計時器的例子:
Imports System.Threading
Public Class Form1
Dim WithEvents timer As New System.Windows.Forms.Timer()
Dim counter As Integer = 0
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
timer.Interval = 1000 ' 設置計時器間隔為1秒
timer.Enabled = False ' 初始化時不啟動計時器
End Sub
Private Sub btnStart_Click(sender As Object, e As EventArgs) Handles btnStart.Click
counter = 0 ' 重置計時器
timer.Start() ' 啟動計時器
End Sub
Private Sub btnStop_Click(sender As Object, e As EventArgs) Handles btnStop.Click
timer.Stop() ' 停止計時器
End Sub
Private Sub timer_Tick(sender As Object, e As EventArgs) Handles timer.Tick
counter += 1 ' 計時器自增1
lblCounter.Text = counter.ToString() ' 更新顯示的計數器數值
End Sub
End Class
上面的代碼創建了一個簡單的窗體應用程序,包含了一個開始按鈕(btnStart)、停止按鈕(btnStop)和一個用于顯示計數器數值的標簽(lblCounter)。當用戶點擊開始按鈕時,計時器開始計數,每隔1秒更新計數器數值,并在標簽上顯示出來。當用戶點擊停止按鈕時,計時器停止計數。