我将如何停止的形式vb.net都定时器(How will i Stop all timers in

2019-10-18 10:37发布

我创建具有计时器(作为提醒)动态形式作为通知或警报的形式。 i各自表单上分配一个名称。

所以每当它被更新..我想关闭或某些表格上禁用计时器,以便它永远不会显示(如警报)。

在每个控制找到计时器不工作,我不能禁用它。

 For Each f As Form In My.Application.OpenForms


        If (f.Name = Label10.Text) Or (f.Name = "notification" & Label9.Text) Then

           Dim timer = Me.components.Components.OfType(Of IComponent)().Where(Function(p) p.[GetType]().FullName = "System.Windows.Forms.Timer").ToList()
              For Each cmd In timer
                  If Not cmd Is Nothing Then
                        Dim tmp As Timer = DirectCast(cmd, Timer)
                           tmp.Enabled = False
                           tmp.Stop()
                  End If
              Next

       End If

 Next

我将如何改变(Me.Components.Components)至f这是我的形式(f.Components.Components),请帮助我。

Answer 1:

在通过窗体上的计时器,以循环中,您需要先得到他们的举行。 控件集合不包含任何计时器对象。 定时器写在非托管的C / C ++微软的代码,只有很少的包装,以支持其在.NET API。

您仍然可以访问,虽然他们通过有点finagling的。 我已经测试了下面的代码,它确实与形式1个定时器工作。 我还没有超过1个定时器试过,但它应该工作。

Dim timer = Me.components.Components.OfType(Of IComponent)().Where(Function(p) p.[GetType]().FullName = "System.Windows.Forms.Timer").ToList()
    For Each cmd In timer
        If Not cmd Is Nothing Then
            Dim tmp As Timer = DirectCast(cmd, Timer)
            tmp.Enabled = False
            tmp.Stop()
        End If
    Next

这段代码的另一个版本可能看起来像这样带着几分LINQ优化的事情:

Dim timer = Me.components.Components.OfType(Of IComponent)().Where(Function(ti) ti.GetType().FullName = "System.Windows.Forms.Timer").ToList()
    For Each tmp As Timer In (From cmd In timer Where Not cmd Is Nothing).Cast(Of Timer)()
        tmp.Enabled = False
        tmp.Stop()
    Next


文章来源: How will i Stop all timers in a form vb.net