How will i Stop all timers in a form vb.net

断了今生、忘了曾经 提交于 2019-12-24 17:18:57

问题


I create dynamic form with timer(as a reminder) as a notification or alert form. i assign a name on each form.

so whenever it is updated.. i want to close or to disable the timer on that certain form so it will never show (as an alert).

the for each control to find timer doesn't work, i can't disable it.

 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

How will i change (Me.Components.Components) to f which is my form (f.Components.Components) please help me.


回答1:


In order to loop through the timers on the form you need to first get a hold of them. The controls collection does not contain any timer objects. Timers were written in unmanaged C/C++ code by microsoft and only have little wrappers to support their API in .NET.

You can still access them though through a bit of finagling. I have tested the following code and it does work with 1 timer on the form. I have not tried it with more than 1 timer, but it should work.

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

Another version of this code could look like this with a bit of LINQ optimization going on:

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


来源:https://stackoverflow.com/questions/18070297/how-will-i-stop-all-timers-in-a-form-vb-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!