我正在开发2D游戏(pacman)以通过c#在VB 2013中提高自己, 并且我希望通过单击特定按钮激活我的按键事件。(这是游戏结束时显示的重启按钮)。感谢您的帮助。
//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)
{
}
答案 0 :(得分:0)
在这里进行一些重构可能会有所帮助。假设如果按下按钮,则使用的键代码为Keys.Down。在这种情况下,您可以将Form_KeyDown中的所有代码移动到另一个名为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);
}
现在您可以从Form_KeyDown事件中调用此方法
private void Form_KeyDown(object sender, KeyEventArgs e)
{
// Pass whatever the user presses...
HandleKey(e.KeyCode);
}
并点击按钮
private void button1_Click(object sender, EventArgs e)
{
// Pass your defined key for the button click
HandleKey(Keys.Down);
}