简体   繁体   English

键盘按下会冻结计时器C#

[英]keydown freezes timer c#

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'. 我还使用keydown事件来处理用户移动“青蛙”时的情况。 So, w moved up, s moves down etc. 因此,w向上移动,s向下移动等。

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. 这意味着如果用户只是按住“ w”或向上按住,则所有汽车都将停止移动。

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? 有没有办法将计时器放在后台工作人员中,或者使计时器即使在用户移动的情况下也能继续滴答作响?

Thanks for any help! 谢谢你的帮助!

This is what I currently have: 这是我目前拥有的:

    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);
        }
     }

A background thread or worker is the solution. 解决方案是使用后台线程或工作程序。 Here is a simple background worker. 这是一个简单的后台工作者。

        BackgroundWorker bw = new BackgroundWorker();
        bw.DoWork += new DoWorkEventHandler(bw_DoWork);
        bw.RunWorkerAsync();
    }


    static Timer _t;
    static void bw_DoWork(object sender, DoWorkEventArgs e)
    {
        _t = new Timer();
        _t.Start();
    }

Look at the Output window when you run your program with the debugger. 使用调试器运行程序时,请查看“输出”窗口。 You'll see lots of IllegalOperationException messages. 您会看到很多IllegalOperationException消息。 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. 后台工作程序方法死于异常,您没有注意到它是因为您没有在DoWorkCompleted事件处理程序中检查e.Error属性。 That's why it ain't moving. 这就是为什么它不动。

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. 您将需要放弃使用线程来实现UI逻辑的想法。 Games are usually implemented with a game loop . 游戏通常通过游戏循环来实现。

You need to implement a thread to run in the background that keeps track of the timer or use a Backgroundworker class to do this for you. 您需要实现一个在后台运行以跟踪计时器的线程,或者使用Backgroundworker类为您执行此操作。 If you want precision Timer, use the System.Threading.Timer class. 如果要使用精密Timer,请使用System.Threading.Timer类。

Hope this helps, Best regards, Tom. 希望这对您有所帮助,汤姆,谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM