C# 在循环C表单应用程序中使用Keyboard.IsKeyDown

C# 在循环C表单应用程序中使用Keyboard.IsKeyDown,c#,winforms,C#,Winforms,我正在尝试在windows c窗体中制作一个platformer游戏,在我的主游戏循环中,我有一些代码,但我似乎无法让用户输入正常工作,任何帮助都将不胜感激 这是我的代码: 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

我正在尝试在windows c窗体中制作一个platformer游戏,在我的主游戏循环中,我有一些代码,但我似乎无法让用户输入正常工作,任何帮助都将不胜感激

这是我的代码:

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);
}
每当我运行这个程序时,程序就会停止响应并最终崩溃
当我按下insert键或我使用的任何其他键时,它都不起作用

假设此代码正在表单中运行,您应该订阅表单的事件:

因此,如果用户按下键,就会调用KeyDownHandler。不需要在阻止UI线程的循环中拉动键盘状态

如果您喜欢在设计器窗口中设置对事件的订阅和KeyPreview值,而不是编写自己的代码,那么也可以在设计器窗口中设置


顺便说一句:键盘类是WPF的一部分。你不应该把它和Windows窗体混在一起。

你是在后台进行更新吗?这显然没有响应,因为它总是忙于运行循环和睡眠……我不明白这个问题,你能详细说明一下background@markbenovsky是什么吗?那么为什么我长时间按insert时什么都没发生呢@RenéVogtYou正在调用Thread.Sleep在UI线程上的无限循环中。是否只有在使用事件处理程序按下任何键时,才可以执行一行代码,而是使用if语句,就像在控制台应用程序中使用命令console.ReadKeytrue;?你想在哪里做?如果您以这种方式等待密钥,您将始终阻止UI。
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
    }
}