2017-02-02 47 views
0

在我的項目中我需要修改這個預製代碼來改變遊戲的佈局。所以我想在我的表單上添加關鍵事件以便導航到'WASD',而不是使用按鈕來移動蛇。但是這裏的問題是,一旦我將該函數添加到窗體並測試它在控制檯上顯示出來,它不會給出任何事件,而不會發生事件錯誤。我不是這方面的專家,所以我希望有足夠的人帶領我走上正確的道路,謝謝。winform中的關鍵事件問題c#

這是我的項目的代碼和屏幕截圖。

public Form1() 
    { 
     InitializeComponent(); 

     backgroundMusic.PlayLooping(); 


     this.AutoSize = true; 
     boardPanel.AutoSize = true; 

     //Set up the main board 
     mainBoard = new Board(this); 

     //Set up the game timer at the given speed 
     clock = new Timer(); 
     clock.Interval = speed; //Set the clock to tick every 500ms 
     clock.Tick += new EventHandler(refresh); //Call the refresh method at every tick to redraw the board and snake. 

     duration = 0; 
     score = 0; 
     level = 1; 
     modeLBL.Text = mode; 

     gotoNextLevel(level); 

    } 

    private void keyDown(object sender, KeyEventArgs e) 
    { 
     if (e.KeyData == Keys.W) 
     { 
      Console.WriteLine("W is pressed"); 
     } 
    } 
} 

設計視圖的窗體。 Design view of the form

+0

您還沒有實際註冊的處理程序' this.KeyDown = new KeyEventHandler(keyDown);' –

回答

3

你的問題是通常你Form上的Control之一將有焦點和捕獲所有關鍵事件。

爲了使您的FormKeyDown事件時,而子控件具有焦點按下一個鍵,設置您Form到真正的KeyPreview屬性:

public Form1() 
{ 
    InitializeComponent(); 

    backgroundMusic.PlayLooping(); 

    this.AutoSize = true; 
    this.KeyPreview = true; // <-- add this line 
+0

我相信這應該是正確的答案。 99.9%的鍵盤按下的問題歸結爲形式.KeyPreview – Stavm

+0

感謝您的快速響應,起初我試圖尋找'keyPreview'但無處可尋,現在我知道我需要輸入它代碼本身,而不是從窗體的屬性菜單中查找。哈哈.. – Jatiz

+0

@Jatiz,但它實際上是在窗體的屬性窗口:)「KeyPreview」之間「IsMdiContainer」和「語言」(如果按字母順序排序)。 –