c# - 如何在 Timer Tick 事件上使用 TimeSpan 显示秒数

标签 c# winforms

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

编辑

我试过 timer1.Interval = 1000;
examTime = examTime.Subtract(TimeSpan.FromSeconds(1));

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

        public SubjectExamStart()
        {
            InitializeComponent();

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

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

最佳答案

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

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

关于c# - 如何在 Timer Tick 事件上使用 TimeSpan 显示秒数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19679570/

相关文章:

c# - 以编程方式设置 closereason

c# - 更新新项目时如何在WinForms ListView控件中自动向下滚动?

c# - 拖放不起作用

c# - 在 DNX PCL 中获取 ApplicationBasePath

c# - 企业库 6 Microsoft.Practices.EnterpriseLibrary.Caching 丢失?

.net - 如何将 Windows 窗体窗体的大小调整为小于 132x38?

c# - 是否有必要在winform控件上调用dispose?

c# - 在 datepicker c# Winforms 上引发验证事件

c# - 带有数字键的动态 json 对象

c# - 在 web.config 文件中添加命名空间有什么好处?