【问题标题】:How to use timer in VB.Net?如何在 VB.Net 中使用计时器?
【发布时间】:2014-08-15 05:18:28
【问题描述】:

我正在尝试在 VB.Net 中编写迪斯科灯光机。 我在 WPF 上有四个椭圆,我希望它们“点亮”(=将填充从白色更改为某种颜色),然后 等待 0.5 秒,然后将填充改回白色 -一切都按照预先写好的顺序。

我正在尝试使用 DispatherTimer,但我实际上并不知道如何使它工作。 省略号是名称 pad0、pad1 等...

Public Sub timer()
    Dim t As New System.Windows.Threading.DispatcherTimer()
    AddHandler t.Tick, AddressOf dispatcherTimer_Tick
    t.Interval = New TimeSpan(0, 0, 1)
End Sub

Private Sub dispatcherTimer_Tick(ByVal sender As Object, ByVal e As EventArgs)
End Sub

Private Sub play_Click(sender As Object, e As RoutedEventArgs) Handles play.Click
    Dim sequence = New Integer() {1, 0, 3, 2}
    For i As Integer = 0 To 3
        Select Case sequence(i)
            Case 0
                pad0.Fill = Brushes.Blue
                **this is where I want the timer to run!**
                padOff(pad0)
            Case 1
                pad1.Fill = Brushes.Yellow
                **this is where I want the timer to run!**
                padOff(pad1)
            Case 2
                pad2.Fill = Brushes.Green
                **this is where I want the timer to run!**
                padOff(pad2)
            Case 3
                pad3.Fill = Brushes.Red
                **this is where I want the timer to run!**
                padOff(pad3)
        End Select
    Next
End Sub

Public Sub padOff(ByVal pad As Shape)
    pad.Fill = Brushes.White
End Sub

【问题讨论】:

  • 这是一个事件驱动的世界。没有油漆,没有派对
  • 只是一个注释。 Brushes 类中有很多预定义的画笔,例如Brushes.White。无需创建自己的。
  • @Clemens 谢谢,我已经更新了我的代码。

标签: wpf vb.net dispatchertimer


【解决方案1】:

UI 仅在您的代码执行全部后更新。因此,您看不到蓝色的变化。更糟糕的是,您的 UI 会完全冻结 0.5 秒。

正确的做法是:

  1. 将颜色设置为蓝色
  2. Set a timer 将在 0.5 秒后过期并将颜色设置为白色。

其他选择包括:

  • 启动一个新的 Thread 等待 0.5s 然后改变颜色(一定要在这里使用 Dispatcher.Invoke 来改变 UI 线程中的颜色)或者
  • start a BackgroundWorker 等待 0.5s 并更改 RunWorkerCompleted 中的颜色(已在 UI 线程中执行),或者,
  • 使用 asnyc 等待(例如 await Task.Delay(500)),这会导致 UI 在等待期间更新并做出响应。

【讨论】:

  • 这是 WPF。请不要使用 Timer 和 Control.Invoke。取而代之的是DispatcherTimer
  • @Clemens:点了,我把“计时器”小写了。请注意,它后面的链接已经链接到DispatcherTimer 的描述,这是 WPF 的正确计时器。
  • @Clemens:啊,是的,它是 WPF 中的 Dispatcher.Invoke。谢谢,已修复。
  • @Heinzi 谢谢。我正在尝试使用计时器。我已经更新了我的代码,但仍然不知道如何使它工作。很高兴获得更多帮助。
猜你喜欢
  • 1970-01-01
  • 2013-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-18
  • 2021-03-27
  • 1970-01-01
相关资源
最近更新 更多