At a guess, I'm going to say that you found this snippet of code in this repository:
GitHub - mirkoBastianini/Snake-Game: Snake game written in C#, with Visual Studio 2015.[
^]. This works because the code is using something known as a game loop. What is happening is that there is a timer event that is triggering several times a second. Each time the timer event is fired, the event checks to see what key is pressed at that point.
This is the game logic at the timer tick:
private void UpdateScreen(object sender, EventArgs e)
{
if (Settings.GameOver)
{
if (Input.KeyPressed(Keys.Enter))
{
StartGame();
}
}
else
{
if (Input.KeyPressed(Keys.Right) && Settings.direction != Direction.Left)
Settings.direction = Direction.Right;
else if (Input.KeyPressed(Keys.Left) && Settings.direction != Direction.Right)
Settings.direction = Direction.Left;
else if (Input.KeyPressed(Keys.Up) && Settings.direction != Direction.Down)
Settings.direction = Direction.Up;
else if (Input.KeyPressed(Keys.Down) && Settings.direction != Direction.Up)
Settings.direction = Direction.Down;
MovePlayer();
}
pbCanvas.Invalidate();
}
An alternative mechanism is to use the KeyPressed or KeyDown event (in WinForms) to detect when a key has been pressed and handle that.