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

本文关键字:激活 keydown 事件 按钮 何通过 单击 | 更新日期: 2023-09-27 17:59:14

我正在开发2D游戏(pacman),以通过c#在VB2013中提高自己,我想通过点击特定按钮来激活我的按键事件。(这是游戏结束时显示的重新启动按钮)。谢谢你的帮助。

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

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

一点重构可能会有所帮助。假设如果您按下按钮,则要使用的键代码为Keys。向下在这种情况下,您可以将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);
}