First of all, i'd suggest to read this:
Five Common Daylight Saving Time Antipatterns of .NET Developers[
^]
If you want to measure elapsed time, i'd recommend to use
Stopwatch[
^] together with
Timer[
^].
Steps to do:
Form 1
1. Drop Timer (
timer1
) on the form
2. Set the following properties:
Interval=100
,
Modifiers=Internal
3. Add Label (
label1
) and set property
Text="00:00:00"
4. Button (
button1
) and set property
Text="Open form 2"
5. Paste below code:
public partial class Form1 : Form
{
private readonly Stopwatch sw = new Stopwatch();
public Form1()
{
InitializeComponent();
sw.Start();
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
label1.Text = sw.Elapsed.ToString(@"hh\:mm\:ss");
}
public string ElapsedTime
{
get => label1.Text;
}
private void button1_Click(object sender, EventArgs e)
{
Form2 frm = new Form2(this);
frm.Show();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
timer1.Stop();
sw.Stop();
}
}
Form 2
1. Add Label (
label1
) and set property
Text="00:00:00"
2. Button (
button1
) and set property
Text="Close"
3. Paste below code:
public partial class Form2 : Form
{
Form1 frm;
public Form2(Form1 f)
{
InitializeComponent();
frm = f;
label1.Text = frm.ElapsedTime;
frm.timer1.Tick += OnTimerTick;
}
private void button1_Click(object sender, EventArgs e)
{
frm.timer1.Tick -= OnTimerTick;
this.Close();
}
private void OnTimerTick(object sender, EventArgs e)
{
label1.Text = frm.ElapsedTime;
}
}
Build project and have a fun!