0

I activated my windows timer and tried to stop but it seems not to be working, please see my code:

private void button1_Click(object sender, EventArgs e)
{
        timer1.Start();
}

private void timer1_Tick(object sender, EventArgs e)
{
        MessageBox.Show("Hello");
        timer1.Stop();
}

It shows the message over and over again and it doesn't stop. Please give me some ideas, I am very grateful for your help.

Hoang Viet
  • 346
  • 1
  • 3
  • 10

2 Answers2

2

You need to stop the timer before showing the message box. Otherwise they may pile up.

There is the System.Timers.Timer that can be configured to be a one-shot timer, but the general approach for other timers is:

When the timer event fires, stop the timer, do your thing and then start the timer again if needed.

Thorsten Dittmar
  • 55,956
  • 8
  • 91
  • 139
  • Thanks for your answer. Is there any way to re-execute the timer n times? "For" loop with n times doesn't work. – Hoang Viet Jan 16 '17 at 09:08
  • Sure. You need a class variable like `int timerRanHowManyTimes = 0` and in every timer event, the variable is increased. Only restart the timer in its event when the value of that variable is less than the desired number of times. – Thorsten Dittmar Jan 16 '17 at 09:31
0

At line MessageBox.Show("Hello"); The execution will stop there waiting for the user to press "OK" button, so line timer1.Stop(); won't be reached until user interacts with the message box, and the timer will continue to work this way.

Ali Ezzat Odeh
  • 2,093
  • 1
  • 17
  • 17