I've been trying to create a countdown timer(from 30 minutes) in a c# winforms application that has the ability to pause, and then resume from where the pause took place. I've tried a number of solutions to achieve this as I know there isn't a specific pause function of the System.Windows.Forms.Timer. I've scoured the internet but couldn't find anything that I could apply to my scenario. Everything I've tried either results in the timer starting again from 30 minutes, or continuing from where it would have been without a pause. This is driving me mad. Can anybody help or suggest an alternative way of doing this? This is my first post here so apologies if I've made any errors. Code below. I've commented out the code that is causing me an issue - I know it's not correct, either syntactically or logically.
public partial class FormWithTimer : Form
{
System.Windows.Forms.Timer timerx = new System.Windows.Forms.Timer();
DateTime startTime = DateTime.Now;
DateTime stopTime = DateTime.Now;
public FormWithTimer()
{
InitializeComponent();
TimerLabel.Text = "30:00";
}
private void Form1_Load(object sender, EventArgs e)
{
}
void timer_Tick(object sender, EventArgs e)
{
}
public void StartButton_Click(object sender, EventArgs e)
{
startTime = DateTime.Now;
BeginTextBox.Text = startTime.ToString();
TimerLabel.Visible = true;
timerx.Tick += (obj, args) =>
TimerLabel.Text = (TimeSpan.FromMinutes(30) - (DateTime.Now - startTime)).ToString("mm\\:ss");
timerx.Enabled = true;
}
public void PauseButton_Click(object sender, EventArgs e)
{
if (PauseButton.Text == "Pause")
{
timerx.Stop();
PauseButton.Text = "Start";
stopTime = DateTime.Now;
}
else
{
PauseButton.Text = "Pause";
timerx.Start();
TimerLabel.Visible = true;
//timerx.Tick += (obj, args) =>
// TimerLabel.Text = (TimeSpan.FromMinutes(30) - (DateTime.Now - (startTime - stopTime))).ToString("mm\\:ss");
timerx.Enabled = true;
}
}
}
I guess you are trying to have the timer continue where it was when it got paused.
To do that, I would suggest using stopTime
for that matter:
In your "Pause-Unpause"- Routine:
public void PauseButton_Click(object sender, EventArgs e)
{
if (PauseButton.Text == "Pause")
{
timerx.Stop();
PauseButton.Text = "Start";
stopTime = DateTime.Now;
}
else
{
PauseButton.Text = "Pause";
startTime += (DateTime.Now - stopTime);
timerx.Start();
TimerLabel.Visible = true;
timerx.Enabled = true;
}
}