WinForms中的计时器在窗体关闭后不会停止。

3
我有一个上下文应用程序,它创建新的表格以向用户显示一些信息。该用户可以使用按钮关闭表单。然而,90秒后,表单会自动关闭,但首先会弹出一个MessageBox来通知用户。
现在我很难知道为什么在第一次关闭表单后,每90秒会再次弹出MessageBox。
我使用Windows.Forms.Timer进行90秒自动关闭,并使用Form.Close将其关闭。我将表单添加到带有其ID的字典中以进行一些管理操作。
创建表单:
MainForm myform = new MainForm();
myform.plate = eventData.iPlate;
myform.tag = eventData.iTag;
formulario.image = eventData.Image;
formulario.PopulateMyFields();
ActivePopUps.Add(eventData.ide, myform);
myform.Show();

现在使用字典来关闭它们

foreach (var popup in ActivePopUps)
{
    if (popup.Key == eventData.some_id)
    {
        try
        {
            popup.Value.Close();
        }
        catch { }
        ActivePopUps.Remove(popup.Key);
    }
}

在主窗体中创建的计时器。
mytimer = new System.Windows.Forms.Timer();
timer_mytimer .Interval = Properties.Settings.Default.ClosingTime; // 90000
mytimer.Tick+=new EventHandler(mytimerEvent);
mytimer.Enabled = true;
mytimer.Start();

实际计时器事件

private void mytimerEvent(object sender, EventArgs e)
{
    MessageBox.Show("Hey ! Closing this one");
    this.Close();
}

我相信在调用.Close()之前可以停止计时器并使其停止,但我的问题是.... Close难道不应该这样做吗?甚至调用.Dispose()也一样?为什么计时器仍然在工作,还有什么其他的在后台幸存下来了呢?


8
提示:如果您使用表单设计器添加计时器,您将会注意到源代码中的差异,这一行:this.timer1 = new System.Windows.Forms.Timer(this.components); - Sinatr
1
this.Close 意味着关闭窗体,而不是计时器。您可以从代码中实例化计时器,因此它是独立于窗体的对象。 - Cee McSharpface
1
使用 mytimer.Enabled = false; 在关闭表单之前关闭计时器。您也可以将其放在 Form_Closed 事件中。 - Jeroen van Langen
@Sinatr 谢谢。那真是太美了 :) - RRhoads
1个回答

0

仅澄清一下。Sinatr在他的评论中提供了正确的答案,因此问题得到了完美的解答,我的代码也正常工作。

在创建计时器时,我漏掉了以下内容:

this.mytimer = new System.Windows.Forms.Timer(this.components)

通过这样做,计时器与表单相关联,以便在表单调用Close()时被处理。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接