c# - 时间跨度减去秒表倒计时

标签 c# .net winforms timer subtraction

我正在使用 WinForm 的。我的表单中有一个标签,应该从 0:20 秒开始倒计时。到 0:00 秒。我在这里尝试这样做,但编译器给我一个错误。

Error: Cannot convert from 'int' to 'System.TimeSpan'

为什么我不能使用 timespan.Subtract()?以及如何从 0:20 倒数到 0:00 秒?

    private void timer1_Tick(object sender, EventArgs e)
    {
        TimeSpan timespan = TimeSpan.FromSeconds(20);

        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();
        Time_label.Text = timespan.Subtract(stopwatch.Elapsed.Seconds);
    }

最佳答案

一个简单的秒计数器的更好方法是使用 Timer 本身。

private readonly Timer _timer;    
private TimeSpan _timespan;
private readonly TimeSpan _oneSecond;

public Form1()
{
    InitializeComponent();

    _timer = new Timer();
    _timer.Tick += timer1_Tick;
    _timer.Interval = 1000;       

    _timespan = TimeSpan.FromSeconds(20);
    _oneSecond = new TimeSpan(0, 0, 0, 1);

    _timer.Start();
}

private void timer1_Tick(object sender, EventArgs eventArgs)
{
    if (_timespan >= TimeSpan.Zero)
    {
        Time_label.Text = _timespan.ToString(@"m\:ss");
        _timespan = _timespan.Subtract(_oneSecond);
    }
    else
    {
        _timer.Stop();
    }
}

关于c# - 时间跨度减去秒表倒计时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40473726/

相关文章:

c# - 如何比较组合框中的新值和先前值?

c# - 如何在像素艺术编辑器中优化绘制区域

c# - 通过 cookie 控制对页面的访问

C# StreamReader 可以检查当前行号吗?

c# - 如何更改没有 ID 的类 css 的属性?

c# - 如何在 C# 中过滤和组合 2 个数据集

c# - 如何将 DataGridView 内容转换为自定义对象的 List<>?

c# - Openxml - 锁定所有内容控件

c# - 使用 C# WebBrowser 时是否可以检测到调用的任何 javascript 函数

以编程方式编辑 DataGridView 后,C# 更新 MySql