开发者

.NET Timer Control

I have a windows app which is just a form with a timer开发者_如何转开发 control on. I've managed to track this down to the following situation:

private void timer1_Tick(object sender, EventArgs e)
{
    MessageBox.Show("Test");
    timer1.Enabled = false;
}

Will print Test again and again until I stop the program. However:

    private void timer1_Tick(object sender, EventArgs e)
    {
        //MessageBox.Show("Test");
        textBox1.Text += "t";
        timer1.Enabled = false;            
    }

Just adds a single "t" to the textbox.

Can anyone tell me why MessageBox.Show is causing the function to return before the timer is disabled?


The call to MessageBox.Show blocks execution of timer1_Tick until you close the messsagebox, so the call to set timer1.Enabled = false; doesn't occur until after that. Because of this, the timer is still running and thus timer_Tick` still keeps getting called, every time the timer fires, until you hit OK on one of the message boxes.

What you need, if you want displaying the messagebox to stop the timer from firing again, is:

private void timer1_Tick(object sender, EventArgs e)
{
    timer1.Enabled = false;
    MessageBox.Show("Test");
}


You disable the timer after the user clicked the messagebox away.

MessageBox.Show shows a modal dialog. It will return (to the caller method) after the user responded to the messagebox. If you disable the timer first, the event will not be triggered again, and the user will have enough time to react.

Try this:

  timer1.Enabled = false;
  MessageBox.Show("Test");


Are you clicking OK on test, each timer click? If the message boxes keep stacking up one on top of the other, it's because MessageBox.Show doesn't return until you close the messagebox. In the meantime a message pump will continue to run, and process your timer messages.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜