我需要在表单加载 10 秒后显示一条消息。 我正在使用下面的代码
private void Form1_Load(object sender, EventArgs e)
{
SetTimeInterval();
}
System.Windows.Forms.Timer MyTimer = new System.Windows.Forms.Timer();
public void SetTimeInterval()
{
MyTimer.Interval = ( 10 * 1000);
MyTimer.Tick += new EventHandler(TimerEventProcessor);
MyTimer.Start();
}
void TimerEventProcessor(Object myObject,EventArgs myEventArgs)
{
MessageBox.Show("TIME UP");
MyTimer.Stop();
MyTimer.Enabled = false;
}
尝试使用 MyTimer.Stop() 和 MyTimer.Enabled = false,但消息框每 10 秒显示一次。如何在一审后停止它?
最佳答案
您的问题是 MessageBox.Show()
是一个阻塞 调用。所以 MyTimer.Stop()
仅在关闭 MessageBox
后调用。
因此,在您关闭 MessageBox
之前,每隔 10 秒就会弹出一个新消息框。简单的解决方案是更改调用顺序:
void TimerEventProcessor(Object myObject,EventArgs myEventArgs)
{
MyTimer.Stop();
MyTimer.Enabled = false;
MessageBox.Show("TIME UP");
}
因此,在显示消息框之前,一旦您进入事件处理程序,计时器就会停止。
关于c# - System.Windows.Forms.Timer 继续运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39203850/