× Main Menu

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

Adding the Code –

We need to make the events link with the XML files, we added those lines of code before where in the CANVAS tag we put in key down and key up tags. Now it’s time to link them together.

Right click on the Canvas_KeyDown keyword and click on Go to Definition. Do the same for the Canvas_KeyUp keyword. This will automatically add the syntaxes for the event in the code.

Lets take a look the C# code now Click on the MainWindow.XAML.CS tab on top of the display

And it will take you to the C# code view.

This is the default view of the code, now we need to start adding our own logic to it, lets start with adding a namespace that’s needed for the timer.

using System.Windows.Threading;

This is what we need to make the timer work, lets add this right at the top of the script

You will see the list of the in the beginning of the file, just add this to the end and it will be fine. This line will allow us to call the timer and use it in this project. All those using System commands are called Name Spaces these commands are used to add any functionalities to the app. The one we have added now has the TIMER class inside it and we need it to make this app work.

Note- The green text next to it are comments, we have added it so it’s easier for you to see which name space to add for this program.

Now lets add the variables for this program. We need 4 total variables, see below.

Notice where the variables have been inserted. All of these are global variables they can be changed in any function inside of this application. First you have the integer and then 4 Booleans going up, down, left and right. These Booleans will be used to check if the player can go to in that direction and our timer will push the player that way. By default the Booleans are set to false, so we will use that to make sure that player is intending to move in that direction when the relative keys are pressed.

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

%d bloggers like this: