简体   繁体   中英

How can I make the time counter to continue up/down from the current point and not from the start?

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)
        {

        }
    }
}

And in form1

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

When I change the CountUp flag in form1 it's changing the time counter direction up/down but it's starting over each time. Id it's counting up then it start from 00:00:00 and if counting down then from 1 minutes and 40 seconds 00:01:40

How can I make that when I change the flag it will change the direction from the current time and not from the start ?

If the time is for example 00:00:13 (counting up) and I change the flag to count down then count down from 00:00:13 ... 00:00:12... same the other way if it's counting down and I change it to count up then continue up from the current time.

What do you need "_elapsedSeconds" for?

Just use?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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