如何在Timer Tick事件中使用TimeSpan显示秒数

时间:2013-10-30 10:21:19

标签: c# winforms

我使用下面的代码显示hh:mm:ss格式的剩余时间,例如,如果持续时间为30min,它将显示为00:30:00,1分钟后会显示{{1}我怎样才能显示剩余的秒数并相应减少它们。

修改

我尝试了00:29:00
timer1.Interval = 1000;

但它没有让我每秒减少秒数,我该怎么做?

examTime = examTime.Subtract(TimeSpan.FromSeconds(1));

2 个答案:

答案 0 :(得分:3)

要正确执行此操作,您需要跟踪计时器何时启动

DateTime examStartTime;
System.Windows.Forms.Timer runTimer;
TimeSpan totalExamTime = new TimeSpan(1, 30, 0); // Set exam time to 1 hour 30 minutes.

if (runTimer == null)
    runTimer = new System.Windows.Forms.Timer();
runTimer.Interval = 200;
runTimer.Tick -= new EventHandler(runTimerTick);
runTimer.Tick += new EventHandler(runTimerTick);
examStartTime = DateTime.Now;
runTimer.Start();

然后在事件处理程序中,您可以执行以下操作:

public void runTimerTick(object sender, EventArgs e)
{
    TimeSpan currentExamTime = DateTime.Now - examStartTime;
    if (currentExamTime > totalExamTime)
    {
        MessageBox.Show("Exam Time is Finished");
        runTimer.Stop();
        runTimer.Tick -= new EventHandler(runTimerTick);
        runTimer.Dispose();
    }
}

我希望这会有所帮助。

答案 1 :(得分:3)

而不是减去TimeSpan.FromMinutes,您需要从TimeSpan.FromSeconds

中减去
        public SubjectExamStart()
        {
            InitializeComponent();

             examTime = TimeSpan.FromSeconds(double.Parse(conf[1]));
                    label1.Text = examTime.ToString();
                    timer1.Interval = 1000;
                    timer1.Start();
         }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (sender == timer1)
            {
                if (examTime.TotalMinutes > 0)
                {
                    examTime = examTime.Subtract(TimeSpan.FromSeconds(1));
                    label1.Text = examTime.ToString();
                }
                else
                {
                    timer1.Stop();
                    MessageBox.Show("Exam Time is Finished");
                }
            }
        }

如果要在分配给标签时格式化时间跨度值...您可以使用以下..

label1.Text = examTime.ToString(@"dd\.hh\:mm\:ss");