如何在表单中运行多个计时器?

时间:2016-12-02 15:56:04

标签: vb.net timer

我的表格中有50个按钮和1个标签

Private Sub flp_table_paint(sender As Object, e As PaintEventArgs) Handles flp_table.Paint

        Dim i As Integer
        For i = 1 To 50
            Dim btn_tableNo As New Button
            btn_tableNo.Width = 40
            btn_tableNo.Height = 40
            btn_tableNo.Text = i
            AddHandler btn_tableNo.Click, AddressOf TableButtonClicked

            Dim timer As New Timer
            timer.Tag = i

            Me.flp_table.Controls.Add(btn_tableNo)
        Next

End Sub

我尝试做的是,对于我点击的每个按钮,他们将启动自己的计时器并在标签上显示。

示例:

11:00:00 PM - 单击Button1,lb_timer将显示1,2,3,4 ...

11:00:30 PM - 单击Button2,lb_timer将显示1,2,3,4 ...

11:00:45 PM - 再次点击Button1,lb_timer将显示45,46,47,48 ...

11:00:50 PM - 再次点击Button2,lb_timer将显示20,21,22,23 ...

这是我到目前为止尝试的内容,但失败了......

Private Sub TableButtonClicked(ByVal sender As Object, ByVal e As EventArgs)
    Dim currButton As Button = sender
    selectedTable = currButton

    For Each timer As Timer In Me.Controls
        If timer.Tag = selectedTable.Text Then
            timer.Start()
            lb_timer.Text = timer.ToString
        End If
    Next
End Sub

我不知道如何让它发挥作用,请帮助我......

2 个答案:

答案 0 :(得分:1)

这里没有Timer的异步方法和所有按钮的一个eventhandler

' In constructor
AddHandler button1.Click, AddressOf Button_Click
AddHandler button2.Click, AddressOf Button_Click
AddHandler button3.Click, AddressOf Button_Click
' ... rest of buttons


' variable will keep name of the button which number is showing
Private _selectedButtonName As String

Private Async Sub Button_Click(sender As object, e As EventArgs)
    Dim button As Button = DirectCast(sender, Button)
    _selectedButtonName = button.Name

    Dim isRunning As Boolean = (button.Tag IsNot Nothing)
    If isRunning = True Then return

    await StartCounterAsync(button)
End Sub

Private Async Function StartCounterAsync(Button button) As Task
    button.Tag = new object()
    Dim number As Integer = 0
    While True
        await Task.Delay(1000)
        number += 1

        If _selectedButtonName.Equals(button.Name)
            lb_timer.Text = $"{button.Name}: {number}"
        End If
    End While
End Function

如果您想要重置计数器,可以添加CancellationToken

答案 1 :(得分:0)

可悲的是,计时器没有显示经过的时间。用于您的目的的更容易的控件是StopWatch控件。它非常相似,会显示运行时间。

Dim StopWatchTest As New Stopwatch
StopWatchTest.Start()
Dim EllapsedTime As String = StopWatchTest.ElapsedMilliseconds / 1000

但是,由于您希望使用经过的时间不断更新标签,因此您需要一个计时器来在每个刻度处更新标签。

Dim UpdateLabelTimer As New Timer()
UpdateLabelTimer.Interval = 1000 'How often to update your label (in milliseconds)
AddHandler UpdateLabelTimer.Tick, AddressOf Tick
UpdateLabelTimer.Start()

----------

Private Sub Tick()
    lblLabel.text = StopWatchTest.ElapsedMilliseconds
End Sub