温馨提示×

怎么用vb编写简单计时器

vb
小亿
396
2024-01-04 22:09:31
栏目: 编程语言

下面是一个使用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秒更新计数器数值,并在标签上显示出来。当用户点击停止按钮时,计时器停止计数。

1