winforms Timer.stop in vb.net

fkvaft9z  于 2023-10-23  发布在  .NET
关注(0)|答案(3)|浏览(108)

我在一个按钮里有一段代码,用来停止计时器

Private Sub btnStopICMP_Click(sender As Object, e As EventArgs) Handles btnStopICMP.Click
    Timer1.Stop()
End Sub

但5秒后计时器停止。这意味着在按下停止定时器按钮后,定时器将继续工作5秒。有什么建议让它在按下停止按钮的那一刻停止吗?
这是进入计时器的代码,它每秒都会改变颜色。

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        If time = 1 Then
            label1.Color = Color.Gold
        ElseIf time = 2 Then
            label1.Color = Color.White
            time = 0
        End If
        time = time + 1
End Sub

我已经尝试

Private Sub btnStopICMP_Click(sender As Object, e As EventArgs) Handles btnStopICMP.Click
  Timer1.Enabled = False    
  Timer1.Stop()
End Sub

没有任何结果。

ubof19bj

ubof19bj1#

你可以尝试不同的方法。定义一个布尔变量来控制颜色的变化,至于那个定时器,只要让它连续运行就行了。

Dim IsRunning As Boolean = False

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick

    If Not IsRunning Then Exit Sub

    Label1.BackColor = IIf(Label1.BackColor = Color.Gold, Color.White, Color.Gold)

End Sub

Private Sub btnICMP_Click(sender As Object, e As EventArgs) Handles btnICMP.Click
    IsRunning = Not IsRunning
End Sub

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Timer1.Start()
End Sub

Private Sub Form1_FormClosed(sender As Object, e As FormClosedEventArgs) Handles MyBase.FormClosed
    Timer1.Stop()
End Sub
kkbh8khc

kkbh8khc2#

Imports System.Reflection.Emit
Imports System.Windows.Forms.VisualStyles.VisualStyleElement.TaskbarClock

Public Class Form1
    Dim time As Integer
    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        If Time = 1 Then
            Label1.BackColor = Color.Gold
        ElseIf Time = 2 Then
            Label1.BackColor = Color.White
            time = 0
        End If
        time = time + 1

    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Timer1.Stop()

    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Timer1.Start()
    End Sub
End Class
tgabmvqs

tgabmvqs3#

如果修复了这个问题,您的代码应该可以工作,Label1.Color =。这个可以

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Timer1.Interval = 1000
    Timer1.Enabled = True
End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    Static time As Integer = 1
    If time = 1 Then
        Label1.BackColor = Color.Gold '<<<<<
    ElseIf time = 2 Then
        Label1.BackColor = Color.White '<<<<<
        time = 0
    End If
    time = time + 1
End Sub

Private Sub btnStopICMP_Click(sender As Object, e As EventArgs) Handles btnStopICMP.Click
    ' either works
    'Timer1.Enabled = False
    Timer1.Stop()
End Sub

相关问题