Reputation: 45
I am developing 2D game(pacman)to improve myself in VB 2013 via c#, and I want my key-down events activated by clicking specific button.(That is restart button shown when the game is over).Thanks for your help.
//these are my keydown codes
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
int r = pictureBox5.Location.X;
int t = pictureBox5.Location.Y;
if (pictureBox5.Top >= 33)
{
if (e.KeyCode == Keys.Up)
{
t = t - 15;
}
}
if (pictureBox5.Bottom <= 490)
{
if (e.KeyCode == Keys.Down)
{
t = t + 15;
}
}
if (pictureBox5.Right <= 520)
{
if (e.KeyCode == Keys.Right)
{
r = r + 15;
}
}
if (pictureBox5.Left >= 30)
{
if (e.KeyCode == Keys.Left)
{
r = r - 15;
}
}
if (e.KeyCode == Keys.Up && e.KeyCode == Keys.Right)
{
t = t - 15;
r = r + 15;
}
pictureBox5.Location = new Point(r, t);
}
//and that's the button I wanted to interlace with keydown event
private void button1_Click(object sender, EventArgs e)
{
}
Upvotes: 1
Views: 151
Reputation: 216343
A bit of refactoring could help here. Suppose that if you hit the button the keycode to use is Keys.Down. In this scenario you can move all the code inside the Form_KeyDown to a different method called HandleKey
private void HandleKey(Keys code)
{
int r = pictureBox5.Location.X;
int t = pictureBox5.Location.Y;
if (pictureBox5.Top >= 33)
{
if (code == Keys.Up)
t = t - 15;
}
if (pictureBox5.Bottom <= 490)
{
if (code == Keys.Down)
t = t + 15;
}
if (pictureBox5.Right <= 520)
{
if (code == Keys.Right)
r = r + 15;
}
if (pictureBox5.Left >= 30)
{
if (code == Keys.Left)
r = r - 15;
}
// This is simply impossible
if (code == Keys.Up && code == Keys.Right)
{
t = t - 15;
r = r + 15;
}
pictureBox5.Location = new Point(r, t);
}
Now you can call this method from the Form_KeyDown event
private void Form_KeyDown(object sender, KeyEventArgs e)
{
// Pass whatever the user presses...
HandleKey(e.KeyCode);
}
and from the button click
private void button1_Click(object sender, EventArgs e)
{
// Pass your defined key for the button click
HandleKey(Keys.Down);
}
Upvotes: 1