× Main Menu

WPF C# Tutorial – Move an object with Keyboard and Timer in Visual Studio

Time to add the Timer.

In our last tutorial we used only the key down event to move the character across the screen. In WPF timers have changed slightly, in the old Windows form applications we could drag and drop the timer but in WPF we will need to add it separately in the code. From learning prospective this can seem to be backwards but it’s actually better because now we can simply code the time without going back and changing the settings and adding events. The new way we can simply type it up in the c# script and get it working for the game. Pretty Neat.

Lets take a look on how to implement it in this app.


The timers are added inside the MainWindow() function. It’s done this way so when the program loads up we want the timer to start with it. This way we don’t have to press a button or key to start the game. The initialize component function is a default function for the WPF Forms it loads up all of the elements in the GUI and XML.

DispatcherTimer dispatcherTimer = new DispatcherTimer();

This line is calling the timer into the program, we are creating a new timer instance to this program by calling the DispatcherTimer class. This dispatcher timer is included inside the using system windows threading name space we added earlier. Once the instance is created then we can start working to make it tick and add events to it.

dispatcherTimer.Tick += Timer_Tick;

This line above means that with each TICK of this timer it will trigger the Timer_Tick event. Lets simplify it,

dispatcherTimer.Interval = TimeSpan.FromMilliseconds(20);

This line above we are setting up the interval for the timer. The interval is how often the timer should run, think of it as frames per second. If we have 24 frames per second then the timer will run 24 times in 1 second and it becomes easier to animate anything with that functionality. So in this case we are telling the timer to run every 20 milliseconds. This way we can achieved smoother animation when the rectangle is moving across.


This line is starting the timer. We can also use the Stop() line if we want to stop the game. For this application we only want to start the timer and not worry about the rest we will have some more tutorials to work on them.

Comment on this tutorial and let us know how you got on -

%d bloggers like this: