2017-02-03 84 views
-2

我想在Windows c#窗體中製作一臺平臺遊戲,在我的主遊戲循環中我有一些代碼段,但我似乎無法獲取用戶輸入正常工作,任何幫助將不勝感激!在循環中使用Keyboard.IsKeyDown C#窗體應用程序

這是我的代碼:

while (true)// this is still in testing so it should go on forver 
if (Keyboard.IsKeyDown(Key.Insert) == true) 
{ 
btn1.Left = btn1.Left + 1;// btn is a button 
Update(); 
} 
System.Threading.Thread.Sleep(50); 
} 

每當我運行此程序將變得不能響應並最終崩潰 ,當我按下插入或我使用它的任何其他鍵不起作用

+0

你在做背景更新嗎? –

+0

這顯然是沒有迴應,因爲它總是「忙」運行你的循環和睡覺.... –

+0

我不明白這個問題,你可以詳細說明什麼是「背景」@MarkBenovsky –

回答

0

假設這個代碼在Form運行,你應該訂閱FormKeyDown事件:

public partial class YourForm : Form 
{ 
    public YourForm() 
    { 
     InitializeComponent(); 

     KeyDown += KeyDownHandler; // subscribe to event 
     KeyPreview = true; // set to true so key events of child controls are caught too 
    } 

    private void KeyDownHandler(object sender, KeyEventArgs e) 
    { 
     if (e.KeyCode != Keys.Insert) return; 
     btn1.Left = btn1.Left + 1;// btn is a button 
     e.Handled = true; // indicate that the key was handled by you 
     //Update(); // this is not necessary, after this method is finished, the UI will be updated 
    } 
} 

因此,如果用戶按下該鍵,則會調用KeyDownHandler。沒有必要在阻止你的UI線程的循環中拉動鍵盤狀態。


的訂閱的事件和KeyPreview值可以在設計窗口,如果你喜歡設置過,要在自己的代碼編寫。


而btw:Keyboard類是WPF的一部分。您不應該將它與Windows窗體混合使用。

+0

有沒有一種方法來執行一行代碼只有*任何*鍵被按下否通過使用事件處理程序,但通過使用if語句,如控制檯應用程序中您有命令Console.ReadKey(true);? –

+0

你想要做什麼?如果您以這種方式等待某個密鑰,您將永遠阻止您的用戶界面。 –

相關問題