2016-07-30 100 views
0

我正在開發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

回答

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); 
} 
+0

完全gratefull朋友。謝謝 – KAMATLI

+0

很高興能有所幫助。作爲該網站的一個相對較新的用戶,我建議您閱讀(如果您尚未完成)[接受答案的工作原理](http://meta.stackexchange.com/questions/5234/how-does-accepting -an-answer-work) – Steve

+0

立即修正。它應該是Keys枚舉中的一個值 – Steve