C# System.Windows.Forms.Timer继续运行

C# System.Windows.Forms.Timer继续运行,c#,winforms,timer,C#,Winforms,Timer,我需要在表单加载10秒后显示一条消息。 我正在使用下面的代码 private void Form1_Load(object sender, EventArgs e) { SetTimeInterval(); } System.Windows.Forms.Timer MyTimer = new System.Windows.Forms.Timer(); public void SetTimeInterval() { MyTimer.Inte

我需要在表单加载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,但messagebox每10秒显示一次。第一次执行后如何停止它?

您的问题是
MessageBox.Show()
是一个阻塞调用。因此,只有在关闭
消息框后才会调用
MyTimer.Stop()

因此,在您关闭
消息框之前,每隔10秒就会弹出一个新消息框。简单的解决方案是更改调用顺序:

void TimerEventProcessor(Object myObject,EventArgs myEventArgs)
{
    MyTimer.Stop();
    MyTimer.Enabled = false;
    MessageBox.Show("TIME UP");           
}

因此,在显示消息框之前,只要输入事件处理程序,计时器就会停止。

我建议使用这种方法 转到form.designer.cs 写这个代码

this.timer1.Enabled = true;
this.timer1.Interval = 10000;
并在ur.cs文件中执行此操作

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

这对我来说非常有效。

正确答案:-)因此在代码中这一行:MyTimer.Tick+=neweventhandler(TimerEventProcessor);您不需要指定“新建”。下面是更干净的:MyTimer.Tick+=TimerEventProcessor@谢谢。哪一个更容易理解?MyTimer.Stop()或MyTimer.Enabled=false@JanDavidNarkiewicz谢谢你,我会实施的。你能告诉我使用new和不使用b/w的区别吗?实际上,底层代码与分配委托的“new”和“not”完全相同。C#2.0引入了“委托推理”“--某种程度上解释了编译器的功能--它推断您打算在那里创建一个委托,以便它在幕后为您编写代码。许多示例从未清理过以使用委托推理,因此将在许多地方看到1.0和1.1的方式。这与OP的问题有何关系?这不会停止计时器