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

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

问题描述:

我正在开发2D游戏(pacman),通过c#改进自己在VB 2013中,我想通过点击特定按钮来激活我的按键事件(这是游戏结束时显示的重启按钮)。谢谢你的帮帮我。如何通过点击特定的按钮激活keydown事件?

//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

当你按下按钮时,你应该按什么键? Form_Keydown中的代码完全取决于e.KeyCode的值,因此如果没有密钥,则无法使用该代码,因此无法使用该代码。 – Steve

+0

我希望激活所有4种主要方向方式(右下方左侧) – KAMATLI

+0

这是怎么回事甚至可能吗?代码不能全部在一起。在你的form_keydown代码中有一个不可能的if语句。 KeyCode不能等于Keys.Right和Keys.Up。 – Steve

有点重构可以帮助这里。假设如果你点击按钮,键码使用的是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); 
} 
+0

完全gratefull朋友。谢谢 – KAMATLI

+0

很高兴能有所帮助。作为该网站的一个相对较新的用户,我建议您阅读(如果您尚未完成)[接受答案的工作原理](http://meta.stackexchange.com/questions/5234/how-does-accepting -an-answer-work) – Steve

+0

立即修正。它应该是Keys枚举中的一个值 – Steve