【问题标题】:How can I make the time counter to continue up/down from the current point and not from the start?如何使时间计数器从当前点继续向上/向下,而不是从一开始?
【发布时间】:2021-10-27 20:28:30
【问题描述】:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Extract
{
    public partial class TimeCounter : Label
    {
        public bool CountUp { get; set; }

        private Timer _timer;
        private int _elapsedSeconds;
        private TimeSpan ts = TimeSpan.FromSeconds(100);

        public TimeCounter()
        {
            InitializeComponent();

            StartCountDownTimer();
        }

        public void StartCountDownTimer()
        {
            _timer = new Timer
            {
                Interval = 1000,
                Enabled = true
            };
            _timer.Tick += (sender, args) =>
            {
                if (CountUp == false)
                {
                    ts = ts.Subtract(TimeSpan.FromSeconds(1));
                    this.Text = ts.ToString();
                }
                else
                {
                    _elapsedSeconds++;
                    TimeSpan time = TimeSpan.FromSeconds(_elapsedSeconds);
                    this.Text = time.ToString(@"hh\:mm\:ss");
                }
            };
        }

        private void TimeCounter_Load(object sender, EventArgs e)
        {

        }
    }
}

在form1中

private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if(checkBox1.Checked)
            {
                timeCounter1.CountUp = true;
            }
            else
            {
                timeCounter1.CountUp = false;
            }
        }

当我更改 form1 中的 CountUp 标志时,它会向上/向下更改时间计数器方向,但每次都会重新开始。如果它正在计数,则从 00:00:00 开始,如果倒计时,则从 1 分 40 秒 00:01:40 开始

我怎样才能做到这一点,当我改变标志时,它会从当前时间而不是从一开始改变方向?

如果时间是例如 00:00:13(向上计数)并且我将标志更改为倒计时然后从 00:00:13 ... 00:00:12... 倒计时... 以另一种方式如果它正在倒计时并且我将其更改为向上计数然后从当前时间继续向上。

【问题讨论】:

    标签: c# winforms


    【解决方案1】:

    你需要“_elapsedSeconds”做什么?

    随便用?

    _timer.Tick += (sender, args) =>
    {
        if (CountUp)
        {
            ts = ts.Add(TimeSpan.FromSeconds(1));        
        }
        else
        {
            ts = ts.Subtract(TimeSpan.FromSeconds(1));            
        }
        this.Text = ts.ToString();
    };
    

    【讨论】:

      猜你喜欢
      • 2021-09-02
      • 1970-01-01
      • 2017-02-05
      • 1970-01-01
      • 1970-01-01
      • 2018-01-29
      • 1970-01-01
      • 2016-03-11
      • 1970-01-01
      相关资源
      最近更新 更多