Okay my last question wasn’t really clear on things, so I deleted it and made this one.
I’m making the game ‘snake’.
What I want is that AFTER I select a difficulty, the keydown on the form needs to work
(you select a difficulty, the snake gets drawn and starts moving, in order for it to move to your preferred direction, you press the arrow keys)
Before I added the difficulties it worked perfectly.
Right now after I select the difficulty and want to play the game, the snake doesn’t move, my keys don’t react in the program.
So my problem = keyDown not working after selecting difficulty.
private void btnNormal_Click(object sender, EventArgs e)
{
timer1.Interval = 250;
btnNormal.Visible = false;
btnEasy.Visible = false;
btnHard.Visible = false;
diffLabel.Visible = false;
timer1.Enabled = true;
down = false;
up = false;
right = true;
left = false;
}
private void btnHard_Click(object sender, EventArgs e)
{
timer1.Interval = 10;
btnNormal.Visible = false;
btnEasy.Visible = false;
btnHard.Visible = false;
diffLabel.Visible = false;
timer1.Enabled = true;
down = false;
up = false;
right = true;
left = false;
}
private void btnEasy_Click(object sender, EventArgs e)
{
timer1.Interval = 500;
btnNormal.Visible = false;
btnEasy.Visible = false;
btnHard.Visible = false;
diffLabel.Visible = false;
timer1.Enabled = true;
down = false;
up = false;
right = true;
left = false;
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Down && up == false)
{
down = true;
right = false;
up = false;
left = false;
}
if (e.KeyData == Keys.Up && down == false)
{
down = false;
right = false;
up = true;
left = false;
}
if (e.KeyData == Keys.Right && left == false)
{
down = false;
right = true;
up = false;
left = false;
}
if (e.KeyData == Keys.Left && right == false)
{
down = false;
right = false;
up = false;
left = true;
}
}
Without having all the code to test it, it is hard to pass a judgement…
However, my guess is that you added button to your form. In this case, if the button still has the focus, the KeyDown event isn’t sent to the form, but to the button.
I would transform the Form1_KeyDown method to the override of the OnKeyDown base method and set PreviewKeys to true in the constructor.