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.
CodePudding user response:
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();
};