VB.Net Timer.Tick Not Firing

时间:2016-08-09 09:40:55

标签: vb.net timer

当某些条件为真时,我试图在状态栏上显示30秒的消息。由于某种原因,启用计时器时Timer.Tick事件没有运行,我很确定我在Tick子上遗漏了一些东西,但是无法弄明白。

这是我的代码:

  Dim StatusSecondsPassed As Integer = 0
    Dim StatusTimer As New Timer()
  Dim StatusTextField As New ToolStripStatusLabel


    Public Function WriteStatus(SS As String)


        If StatusTimer.Enabled = True Then
            StatusTimer.Enabled = False
        End If


        StatusSecondsPassed = 0

        StatusTimer.Interval = 1 * 1000

        StatusTimer.Enabled = True

        Return SS
    End Function

    Public Sub StatusTimer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs)

        Dim cMain_Form As Main_Form

        StatusSecondsPassed += 1

        If StatusSecondsPassed = 30 Then
            cMain_Form.StatusTextBox.Text = ""
        End If


    End Sub

有什么想法吗?我尝试将Handles放在tick子的末尾,但如果我放Handles StatusTimer.Tick

,则会生成错误

1 个答案:

答案 0 :(得分:4)

你需要处理这个事件:

AddHandler StatusTimer.Tick, AddressOf StatusTimer_Tick

此行说明每当Tick事件发生时,您的sub将被调用。

但是,如果您想使用Handles原因,则必须按照以下方式声明您的计时器:

Dim WithEvents StatusTimer As New Timer()

'And your sub
Public Sub StatusTimer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles StatusTimer.Tick

但是,此方法不允许您删除关联。使用AddHandler子句,您可以通过执行以下操作来删除事件侦听器:

RemoveHandler StatusTimer.Tick, AddressOf StatusTimer_Tick