I want to write a simple stopwatch program, I can make it work with the following code
public Form1()
{
InitializeComponent();
}
System.Diagnostics.Stopwatch ss = new System.Diagnostics.Stopwatch { };
private void button1_Click(object sender, EventArgs e)
{
if (button1.Text == "Start")
{
button1.Text = "Stop";
ss.Start();
timer1.Enabled = true;
}
else
{
button1.Text = "Start";
ss.Stop();
timer1.Enabled = false;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
int hrs = ss.Elapsed.Hours, mins = ss.Elapsed.Minutes, secs = ss.Elapsed.Seconds;
label1.Text = hrs + ":";
if (mins < 10)
label1.Text += "0" + mins + ":";
else
label1.Text += mins + ":";
if (secs < 10)
label1.Text += "0" + secs;
else
label1.Text += secs;
}
private void button2_Click(object sender, EventArgs e)
{
ss.Reset();
button1.Text= "Start";
timer1.Enabled = true;
}
Now I want to set a custom start time for this stopwatch, for example I want it not to begin count up from 0:00:00 but to start with 0:45:00
How can I do it, thank you.
Create a new instance of System.TimeSpan with the initial value of 45 minutes as per you example. Than add the value of the stopwatch to it TimeSpan.Add Method. Conveniently the Stopwatch.Elapsed is of type System.TimeSpan already.
Than use string formatter to print the formatted time into the label. I think one of the other answers already shows how to do that. Otherwise here are some good references on how to format a TimeSpan instance TimeSpan.ToString Method (String) or using a custom formatter.