如何通过单击特定按钮激活 keydown 事件?

How to activate keydown event by clicking specific button?

我正在开发 2D 游戏 (pacman) 以在 VB 2013 年通过 c# 提高自己, 我希望通过单击特定按钮激活我的按键事件。(即游戏结束时显示的重启按钮)。感谢您的帮助。

  //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)
    {
    }

一点重构可能会有所帮助。假设如果您按下按钮,要使用的键码是 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);
}