我需要在表单加载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;
}
Run Code Online (Sandbox Code Playgroud)
使用MyTimer.Stop()和MyTimer.Enabled = false尝试,但messagebox每10秒显示一次.如何在第一次实例后停止它?
你的问题是,MessageBox.Show()是一个阻塞调用.所以,MyTimer.Stop()只叫你关闭后的MessageBox.
因此,在你关闭之前MessageBox,每隔10秒会弹出一个新的.简单的解决方案是更改调用顺序:
void TimerEventProcessor(Object myObject,EventArgs myEventArgs)
{
MyTimer.Stop();
MyTimer.Enabled = false;
MessageBox.Show("TIME UP");
}
Run Code Online (Sandbox Code Playgroud)
因此,在显示消息框之前,只要您进入事件处理程序,计时器就会停止.