Written by: Justin Rich
Using System.Windows.Threading DispatcherTimer.Tick event in VB.Net
The DispatherTimer.Tick event is the best way in .Net to create an animation loop for either a game or graphical application, but use of it in VB.Net is tricky. I've seen several articles posted around the internet how to use the DispatherTimer's Tick event with C# and I will show you that here in case you're a C# programmer that happened upon this article:
C#
using System.Windows.Threading;
private DispatcherTimer _dpTimer;
_dpTimer = new DispatcherTimer();
_dpTimer.Interval = TimeSpan.FromMilliseconds(20);
_dpTimer.Tick += new EventHandler(CalledFunction);
_dpTimer.Start();
void CalledFunction(object sender, EventArgs e)
{
}
What you tend to find with this code when translating it to VB.Net is that the .Tick += new EventHandler will not work. It will give you some crazy syntax error about handlers.
To make this work, you have to make sure you're including the System.Windows.Threading class into your form.
Here's how I addressed using the .Tick function in VB.Net
VB
Imports System.Windows.Threading
Private dpTimer As DispatcherTimer
Public Sub New()
dpTimer = New DispatcherTimer
dpTimer.Interval = Timespan.FromMilliseconds(20)
AddHandler dpTimer.Tick, AddressOf CalledSub
dpTimer.Start()
End Sub
Private Sub CalledSub
'Perform your per-tick work here
End Sub
The 20 milliseconds will make your loop run about 30 times per second (assuming there's not any intense workload for the computer running it). VB.Net also will not automatically recognize the .Tick when you add it to the dpTimer variable (doesn't seem to be in the intellisense library) so maybe this is why there aren't many VB.Net articles around using this. Go ahead and type it, and it will allow it's use and don't be discouraged by the lack of intellisense.
I'm using this function for my studies and attempt at game programming in Silverlight 2 and this tick object is essentially how you will make your silverlight application loop around the main function that draws to the screen. You can also be applying this to standard VB.Net programs that are doing graphical drawing to the screen, so it's not limited to Silverlight or game development. I've seen this used in animated window pop-ups similar to the ones that Microsoft uses in Live messenger and Outlook when you get new messages.