如何在日期时间倒数计时器中输入时间 [英] How do I input a time in a datetime countdown timer

查看:122
本文介绍了如何在日期时间倒数计时器中输入时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用计时器组件制作倒数计时器,以剩余剩余时间更新标签。问题是即使间隔设置为1,标签也不会每毫秒更新一次。我在不同的网站上看过那是因为它不是一个真实的环境。



我还制作了一个使用DateTime来计算时间差的计时器使用与倒数计时器相同的计时器组件启动计时器和实际时间。这确实每毫秒更新一次标签。



看到DateTime方法确实每隔毫秒更新标签我想知道,是否可以使用DateTime制作倒数计时器从a减少到设定的时间(小时,分钟,秒,毫秒)的方法?



我尝试了什么:



我搜索了这个,并在网站上阅读了几个主题,其中包括几个,搜索过Microsoft Docs和MSDN,但我无法让它工作。

I've made a countdown timer using the timer component to update a label with the remaining time left. The problem is that even though the interval is set to 1 the label doesn't update every millisecond. I've read on different websites that that's because it's not a real time environment.

I've also made a timer that uses DateTime to calculate the difference between the time the timer is started and the actual time, using the same timer component as with the countdown timer. This does update the label every millisecond.

Seeing as the DateTime method does update the label every millisecond I was wondering, is it possible to make a countdown timer with the DateTime method which counts down from a to set amount of time (hours, minutes, seconds, milliseconds)?

What I have tried:

I've searched about this and read several topics on websites, including several on this one, searched Microsoft Docs and MSDN, but I just can't get it to work.

推荐答案

请参阅此处的CodeProject文章:微秒和毫秒C#定时器 [ ^ ]



此处的倒计时示例:倒数计时器&秒表 - 伊万波波夫 [ ^ ]



请注意,秒表类取决于系统硬件和操作系统: Stopwatch.IsHighResolution Field(System.Diagnostics)| Microsoft Docs [ ^ ]
See CodeProject article here: Microsecond and Millisecond C# Timer[^]

And Countdown example here: Countdown timer & Stopwatch - Ivan Popov[^]

Note that the Stopwatch class depends on the system hardware and operating system: Stopwatch.IsHighResolution Field (System.Diagnostics) | Microsoft Docs[^]


计时器不会以确切的间隔触发,它们通过正常的Windows消息系统进行处理任何方式,形状或形式的时间系统。所有你保证的是计时器滴答事件不会发生在间隔时间内。



所以倒计时的方法是将类级别DateTime设置为结束时间:

Timer's don't "fire" at exact intervals, they are processed via the normal Windows Message system which is not a real time system in any way, shape, or form. All you are guaranteed is that the timer tick event will not happen in less that the interval.

So the way to do a countdown is to set a class level DateTime to the end time:
private DateTime endsAt;
...
   endsAt = DateTime.Now.AddMinutes(5);

然后在Tick处理程序中计算如何剩下的就是:

Then in the Tick handler calculate how much is left:

void countDown_Tick(object sender, EventArgs e)
    {
    int secondsRemaining = (int) (endsAt - DateTime.Now).TotalSeconds;
    myLabel.Text = secondsRemaining.ToString();
    }


这篇关于如何在日期时间倒数计时器中输入时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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