【问题标题】:How to change the label text every 3 seconds using a timer VB.NET如何使用计时器 VB.NET 每 3 秒更改一次标签文本
【发布时间】:2018-11-27 13:39:47
【问题描述】:
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

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

【问题讨论】:

  • 什么是Timer1?您应该使用 System.Windows.Forms.TimerTick 事件来更新 UI。
  • 定时器不是这样工作的,你应该设置Option Strict On

标签: arrays vb.net timer boolean


【解决方案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

【讨论】:

    【解决方案2】:

    您必须将代码放入 Timer 事件中。不在按钮单击事件中。 并在按钮点击事件中启用计时器。

    【讨论】:

      【解决方案3】:

      -添加计时器

      • 将区间设为 3000
      • 在计时器事件中,将标签背景颜色更改为您想要使用的颜色(从 RGB 或使用随机数)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-04-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多