keydown 冻结计时器 c# [英] keydown freezes timer c#

查看:31
本文介绍了keydown 冻结计时器 c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,我正在制作蛙类游戏,我正在使用计时器让图像在屏幕上移动.我还使用 keydown 事件来处理用户移动青蛙"时的情况.所以,w 向上移动,s 向下移动等等.

Hey, I am making a frogger type game and I am using a timer to make the images move across the screen. I am also using the keydown event to handle when the user moves the 'frog'. So, w moved up, s moves down etc.

我遇到的问题是,每当用户按下任何移动按钮时,计时器都会冻结.这意味着如果用户只是按住 'w' 或向上键,所有汽车都会停止移动.

The problem I have come across is that whenever the user presses any movement button, the timer freezes. This means if the user just holds down 'w' or up, all the cars stop moving.

有没有办法将计时器放在后台工作人员中,或者让计时器即使在用户移动时也继续滴答作响?

Is there a way of putting the timer in a background worker or a way to make the timer carry on ticking even when the user is moving?

感谢您的帮助!

这是我目前拥有的:

    public string i;
    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyValue == 68)
        {
            i = "right";
            backgroundWorker1.RunWorkerAsync();
        }
    }


private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        if (i == "right")
        {
            pictureBox1.Location = new Point((pictureBox1.Location.X + 17), pictureBox1.Location.Y);
        }
     }

推荐答案

当您使用调试器运行程序时,请查看输出"窗口.您会看到很多 IllegalOperationException 消息.后台工作方法因异常而死亡,您没有注意到它,因为您没有检查 DoWorkCompleted 事件处理程序中的 e.Error 属性.这就是它不动的原因.

Look at the Output window when you run your program with the debugger. You'll see lots of IllegalOperationException messages. The background worker method is dying on an exception, you are not noticing it because you don't check the e.Error property in a DoWorkCompleted event handler. That's why it ain't moving.

不允许在后台线程中设置控件的属性.这就是异常试图告诉你的.您需要放弃使用线程来实现 UI 逻辑的想法.游戏通常使用 游戏循环.

You are not allowed to set the properties of a control in a background thread. That's what the exception is trying to tell you. You'll need to give up on the idea of using threads to implement your UI logic. Games are usually implemented with a game loop.

这篇关于keydown 冻结计时器 c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆