问题
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