简体   繁体   中英

Timer won't stop after being stopped or disabled

I have a problem with a timer on a form. I've enabled it from the properties and set the interval value 5000. On the tick event, I want to close the current form and open form1, but it's not working. The current form closes and form1 opens every 5 seconds, not only once. What should I do? Thank you in advance!

This is the tick event:

private void timer1_Tick(object sender, EventArgs e)
{
  this.Hide();
  Form1 frm = new Form1();
  frm.ShowDialog();
  timer1.Enabled = false;
}

frm.ShowDialog(); is a blocking call, therefore the next line won't get executed until the new form is closed. Make sure you start by disabling the timer:

private void timer1_Tick(object sender, EventArgs e)
{
    timer1.Enabled = false;
    this.Hide();
    Form1 frm = new Form1();
    frm.ShowDialog();
}

You need to disable the timer before calling the ShowDialog , so move the timer1.Enabled = false; to the first line. Also I suggest that you add the frm.Closed event so that your main form will close after you closed the second form: This is what you want:

timer1.Enabled = false;
Hide();
Form1 frm = new Form1();
frm.Closed += (s, args) => Close();
frm.ShowDialog();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM