Reputation: 43
in my project i need to modified this pre-made code to change the layout of the game. So i want to add key events on my form for my navigation to 'WASD' instead of using a button to move the snake. But the problem here is that once i added the function to the form and test it to display on the console out, it gives nothing, not event error. I am no expert in this, so i hope someone kind enough to lead me to the right path, thanks.
This is the code and screenshot of my project.
public Form1()
{
InitializeComponent();
backgroundMusic.PlayLooping();
this.AutoSize = true;
boardPanel.AutoSize = true;
//Set up the main board
mainBoard = new Board(this);
//Set up the game timer at the given speed
clock = new Timer();
clock.Interval = speed; //Set the clock to tick every 500ms
clock.Tick += new EventHandler(refresh); //Call the refresh method at every tick to redraw the board and snake.
duration = 0;
score = 0;
level = 1;
modeLBL.Text = mode;
gotoNextLevel(level);
}
private void keyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.W)
{
Console.WriteLine("W is pressed");
}
}
}
Upvotes: 0
Views: 254
Reputation: 43896
Your problem is that normally one of the Control
s on your Form
will have the focus and capture all key events.
To enable your Form
raise a KeyDown
event when a key is pressed while a child control has the focus, set the KeyPreview
property of your Form
to true:
public Form1()
{
InitializeComponent();
backgroundMusic.PlayLooping();
this.AutoSize = true;
this.KeyPreview = true; // <-- add this line
Upvotes: 3