How to write a simple timer using VB?

Here is an example of a simple timer written in 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

The code above creates a simple window application that has a start button (btnStart), a stop button (btnStop), and a label (lblCounter) to display the counter value. When the user clicks the start button, the timer starts counting every second and updates the counter value on the label. Clicking the stop button will stop the timer from counting.

bannerAds