Reputation: 21
I want to make a snake game in Windows Forms and dont know how i can detect inputs from a Keyboard. I have read a few solutions and most of them look like that
private void _calendar_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Down:
case Keys.Right:
//action
break;
case Keys.Up:
case Keys.Left:
//action
break;
}
}
But i dont really know how to implement something like this because i have a loop in which i need to detect which arrow key was pressed last. When i try to call that funktion i dont know what parameters i have to give it.
Upvotes: 0
Views: 505
Reputation: 4323
You need to capture the keyevents on the object you are having the snake. So when this is a picture, it needs to be done on the picture's keydown event:
Select the picture box, in the properties (right bottom), select your events. Double click on the KeyDown. Now you will see code like below.
private void PictureBox1_KeyDown(object sender, KeyEventArgs e)
{
}
from here you can start implementing. NO LOOPING NEEDED!
Also while in the game, ensure the picturebox has the focus. If this is not an option, you can consider implementing the event on the form itself.
Upvotes: 0