Search code examples
c#timermessageboxstopwatch

if specific time passed show messagebox in C#


so, i want this: if specific time passed (for example 9 hours) from loading form, than i want to show messagebox said "9 hours passed". my code is this:

public partial class Form1 : Form
{
    Stopwatch stopWatch = new Stopwatch();

    public Form1()
    {
        InitializeComponent();
        stopWatch.Start();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        double sec = stopWatch.ElapsedMilliseconds / 1000;
        double min = sec / 60;
        double hour = min / 60;
        if (hour == 9.00D)
        {
            stopWatch.Stop();
            MessageBox.Show("passed: " + hour.ToString("0.00"));
        }
    }
}

and the problem is that i don't know where to write this part of code:

if (hour == 9.00D)
        {
            stopWatch.Stop();
            MessageBox.Show("passed: " + hour.ToString("0.00"));
        }

so, where i write this code? if you have better way of doing this, please show me.


Solution

  • What people are not appreciating is that it is very unlikely that the double hours will be exactly 9.00! Why not just ask your timer to fire once, after the time you want, 9 hours.

    Timer timer;
    public Form1()
    {
        InitializeComponent();
        timer.Tick += timer_Tick;
        timer.Interval = TimeSpan.FromHours(9).TotalMilliseconds;
        timer.Start();
    }
    
    void timer_Tick(object sender, EventArgs e)
    {
        timer.Stop();
        MessageBox.Show("9 hours passed");
    }