如何使用计时器VB.NET每3秒更改标签文本

时间:2018-11-27 13:39:47

标签: arrays vb.net timer boolean

Dim arr() As String = {"Cake", "Mouse", "Heat", "Tent", "Boots", "Pen", "Stairs", "Cube", "Lion", "Cookies", "Ruler", "Ink"}
Dim timing As Boolean = True
Dim i As Integer = 0
Dim n As Integer = 3000
Private Sub Button1_Click(sender As Object, e As EventArgs)
    Timer1.Start()
    For i = 0 To 11
        While timing = True
            If Timer1.Interval = n Then
                Lbl_Word.Text = arr(i)
                timing = False
            End If
        End While
        timing = True
    Next
    Timer1.Stop()
End Sub

标签的文本没有改变,我不确定自己做错了什么。请帮忙。

3 个答案:

答案 0 :(得分:1)

如果您使用表单计时器,则更新标签的代码必须位于.Tick事件中。下面的代码在事件处理程序中使用静态变量来跟踪要显示的字符串。

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Timer1.Interval = 3000
    If Not Timer1.Enabled Then 'already running?
        Timer1.Start() 'no
    End If
End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    Dim arr() As String = {"Cake", "Mouse", "Heat", "Tent", "Boots", "Pen", "Stairs", "Cube", "Lion", "Cookies", "Ruler", "Ink"}
    'Dim arr() As String = {"Cake", "Mouse", "Heat"} 'to test
    Static idx As Integer = 0 'which index in arr
    If idx < arr.Length Then 'more to show?
        'yes
        Lbl_Word.Text = arr(idx)
        idx += 1
    Else
        'no
        Timer1.Stop()
        idx = 0
    End If
End Sub

不使用计时器的另一种方法。

Private TmrTask As task
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If TmrTask Is Nothing OrElse TmrTask.IsCompleted Then
        TmrTask = Task.Run(Sub() MyTimerTask())
    End If
End Sub

Private Sub MyTimerTask()
    Dim arr() As String = {"Cake", "Mouse", "Heat", "Tent", "Boots", "Pen", "Stairs", "Cube", "Lion", "Cookies", "Ruler", "Ink"}
    'Dim arr() As String = {"Cake", "Mouse", "Heat"} 'to test
    For Each s As String In arr
        Me.BeginInvoke(Sub()
                           Lbl_Word.Text = s
                       End Sub)
        Threading.Thread.Sleep(3000)
    Next
End Sub

答案 1 :(得分:0)

您必须将代码放入Timer事件中。不在Button Click事件中。 并在Button click事件中启用计时器。

答案 2 :(得分:0)

-添加计时器

  • 设置间隔3000
  • 在计时器事件上,将标签背景色更改为您希望可以从RGB使用或使用随机数的颜色