SilverShotBee SilverShotBee - 3 months ago 22
Vb.net Question

VB.Net Timer.Tick Not Firing

I am trying to display a message on a status bar for 30 seconds when certain conditions are true. For some reason, the

Timer.Tick
event isn't running when the timer is enabled, I'm fairly certain I'm missing something on the
Tick
sub, but can't figure it out.

Here's my code:

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


Any ideas? I tried putting
Handles
on the end of the tick sub, but it generates an error if I put
Handles StatusTimer.Tick

Answer

You need to handle the event :

AddHandler StatusTimer.Tick, AddressOf StatusTimer_Tick

This line states that whenever Tick event occurs, your sub will be called.

However, if you want to use the Handles cause, you must declare your timer like this :

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

This method however does not allow you to remove the association. With AddHandler clause, you can remove an event listener by doing :

RemoveHandler StatusTimer.Tick, AddressOf StatusTimer_Tick