我试图每500毫秒制作一个更有效的按钮换色器。我不想制作大量的计时器,所以我想如果我在刻度线上设置一个穿线时间就行了。不。我失败了。我的代码只是同时打开它们。
非常感谢任何帮助实现这一目标。
代码:
Private Sub AnimateButtons_Tick(sender As Object, e As EventArgs) Handles AnimateButtons.Tick
BTN1.BackColor = Color.Red
Threading.Thread.Sleep(500)
BTN2.BackColor = Color.Red
Threading.Thread.Sleep(500)
BTN3.BackColor = Color.Red
Threading.Thread.Sleep(500)
BTN4.BackColor = Color.Red
Threading.Thread.Sleep(500)
BTN5.BackColor = Color.Red
Threading.Thread.Sleep(500)
BTN6.BackColor = Color.Red
Threading.Thread.Sleep(500)
End Sub
答案 0 :(得分:0)
我这里没有太多信息,但根据您使用的控件,计时器将在UI线程上运行。这意味着,只有在" Tick"完了。您需要将计时器设置为500毫秒,并在每个刻度上仅更改一个按钮。像这样:
Dim buttonIndex As Integer = 1 ' Keep the value of which button to change
Private Sub AnimateButtons_Tick(sender As Object, e As EventArgs) Handles AnimateButtons.Tick
If buttonIndex = 1 Then BTN1.BackColor = Color.Red
If buttonIndex = 2 Then BTN2.BackColor = Color.Red
If buttonIndex = 3 Then BTN3.BackColor = Color.Red
If buttonIndex = 4 Then BTN4.BackColor = Color.Red
If buttonIndex = 5 Then BTN5.BackColor = Color.Red
If buttonIndex = 6 Then BTN6.BackColor = Color.Red
End Sub
buttonIndex += 1
您可以将索引初始化为方法中的静态,而不是使用全局变量。我认为这应该有用。
Private Sub AnimateButtons_Tick(sender As Object, e As EventArgs) Handles AnimateButtons.Tick
Static buttonIndex As Integer = 1
If buttonIndex = 1 Then BTN1.BackColor = Color.Red
If buttonIndex = 2 Then BTN2.BackColor = Color.Red
If buttonIndex = 3 Then BTN3.BackColor = Color.Red
If buttonIndex = 4 Then BTN4.BackColor = Color.Red
If buttonIndex = 5 Then BTN5.BackColor = Color.Red
If buttonIndex = 6 Then BTN6.BackColor = Color.Red
buttonIndex += 1
End Sub
如果当然,有更好的"这样做的方式就像使用列表一样,但我希望你能得到一般的想法。
答案 1 :(得分:0)
这会随机设置按钮的背景颜色
Private PRNG As New Random
Private AnimTask As Task
Private isClosing As New Threading.ManualResetEvent(False)
Private Sub AnimateButtons_Tick(sender As Object, e As EventArgs) Handles AnimateButtons.Tick
AnimateButtons.Stop()
AnimTask = Task.Run(Sub()
'random backcolor of these buttons
Dim btns() As Button = {BTN1, BTN2, BTN3}
'the colors
Dim bColors() As Color = {Color.Red, Color.LightYellow, Color.Yellow, Color.LightGreen, Color.LightBlue}
For Each b As Button In btns
Me.BeginInvoke(Sub()
'pick random color
b.BackColor = bColors(PRNG.Next(bColors.Length))
End Sub)
Threading.Thread.Sleep(50)
Next
Me.BeginInvoke(Sub()
If isClosing.WaitOne(0) Then
Me.Close()
Else
AnimateButtons.Start()
End If
End Sub)
End Sub)
End Sub
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
If Not isClosing.WaitOne(0) Then
isClosing.Set()
e.Cancel = True
End If
End Sub