繁体   English   中英

使用C#在Windows Phone应用程序中计数计时器

[英]Count up timer in windows phone application using c#

我已经使用以下代码实现了递增计时器(或秒表)。 我想知道是否存在使用c#在Windows Phone中实现此目标的有效且标准的方法。

任何建议,将不胜感激。

private void start_click()
{
    lhours = 0; lmins = 0; lsecs = 0; lmsecs = 0;
    myDispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 1000); // 1000 Milliseconds 
    myDispatcherTimer.Tick += new EventHandler(Each_Tick);
    myDispatcherTimer.Start();
}
public void Each_Tick(object o, EventArgs sender)
{    
    lsecs = lsecs  + 1;
    if (lsecs > 59)
    {
        lsecs = 0;
        lmins = lmins + 1;
        if (lmins > 59)
        {
            lmins = 0;
            lhours = lhours + 1;
            if (lhours > 23)
            {
                lhours = 0;
                ldays = ldays + 1;
            }
        }
    }

    lblTimerDisplay.Text = ldays + ":" + lhours + ":" + lmins + ":" + lsecs + ":";
}

为什么不使用Stopwatch类?

System.Diagnostics.Stopwatch _sw = new System.Diagnostics.Stopwatch();
private void start_click()
{
    if (!_sw.IsRunning)
    {
        _sw.Start();
    }
    else
    {
        _sw.Stop();
        _sw.Reset();
    }
}
private void Each_Tick(object sender, EventArgs e)
{
    lblTimerDisplay.Text = _sw.Elapsed.ToString();
}

另一种简单的方法是在初始化计时器时保存DateTime.UtcNow,然后在刻度线中从当前DataTime.UtcNow中减去该值。

在计时器初始化时:

DateTime startTime = DateTime.UtcNow;

在刻度上:

TimeSpan elapsedTime = DateTime.UtcNow - startTime; 

然后,您可以使用TimeSpan参数获取显示的天,小时,分钟和秒。

暂无
暂无

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

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