Reputation: 7583
I have a timer on a windows form (C# 3.0, .net 3.5 SP1, VS2008 SP1, Vista) that seems to work even after it is stoppped. The code is:
using System;
using System.Windows.Forms;
namespace TestTimer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
StartTimer();
}
private DateTime deadline;
private void StartTimer()
{
deadline = DateTime.Now.AddSeconds(4);
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
int secondsRemaining = (deadline - DateTime.Now).Seconds;
if (secondsRemaining <= 0)
{
timer1.Stop();
timer1.Enabled = false;
MessageBox.Show("too slow...");
}
else
{
label1.Text = "Remaining: " + secondsRemaining.ToString() + (secondsRemaining > 1 ? " seconds" : " second");
}
}
}
}
Even after the timer1.Stop() is called, I keep reeciving MessageBoxes on the screen. When I press esc, it stops. Howevere, I've expected that only one message box appears... What else should I do? adding timer1.Enabled = false does not change the behavior.
Thanks
Upvotes: 0
Views: 2932
Reputation: 20904
Note that the following is unnecessary:
timer1.Stop();
timer1.Enabled = false;
Stop()
is the same as Enabled=false
. And Start()
is the same as Enabled=true
.
http://msdn.microsoft.com/en-us/library/system.windows.forms.timer.enabled.aspx
Upvotes: 1
Reputation:
A couple of factors may be at work here.
The modal MessageBox.Show() could prevent the timer stop from taking effect until it is dismissed (as Brian pointed out).
The timer1_Tick could be executing on a background thread. UI calls such as MessageBox.Show() and background threads to not mix.
Both issues can be solved by using BeginInvoke to call a method that shows the message box.
Upvotes: 1
Reputation: 118925
I could be wrong, but is MessageBox.Show() a blocking operation (that waits for you to dismiss the dialog)? If so, just move the Show() call to after the Stop/Enabled lines?
Upvotes: 5