2017-02-03 87 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

你想要做什么?如果您以这种方式等待某个密钥,您将永远阻止您的用户界面。 –

相关问题