Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim numberOfForms As Integer = 10
For open = 1 To numberOfForms
TestClosing()
Next
End Sub
我尝试创建的模块代码然后在几秒后关闭表单如下:
Imports System.Timers
Module ClosingModule
Sub TestClosing()
Dim frmNew As New Form
frmNew.Show()
Dim tmr As New System.Timers.Timer()
tmr.Interval = 3000
tmr.Enabled = True
tmr.Start()
End Sub
End Module
我启动了一个计时器,但是我尝试关闭表单的所有方法都与它们创建的顺序相同;不成功; 帮助赞赏;并提前感谢。
答案 0 :(得分:4)
将Timer添加到您正在创建的表单中,在创建表单时启动它,它们将按照创建它们的顺序关闭。我还增加了一个增量延迟,即关闭的顺序更明显。
<强> Form1中强>
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim numberOfForms As Integer = 10
For open = 1 To numberOfForms
Dim frmNew As New Form2
frmNew.Text = open.ToString
frmNew.Show()
Next
End Sub
<强>窗体2 强>
Public Class Form2
Dim myTimer As New Timer()
Private Sub myTimer_Tick(sender As System.Object, e As System.EventArgs)
myTimer.Stop()
Me.Close()
End Sub
Private Sub Form2_Shown(sender As Object, e As System.EventArgs) Handles Me.Shown
myTimer.Interval = 1000 * CInt(Me.Text)
AddHandler myTimer.Tick, AddressOf myTimer_Tick
myTimer.Start()
End Sub
End Class
在模块中添加代码以执行相同的操作:
Imports System.Timers
Module ClosingModule
Sub TestClosing(multiplier As Integer)
Dim frmNew As New Form
frmNew.Show()
Dim tmr As New System.Timers.Timer()
AddHandler tmr.Elapsed, AddressOf Timer_Elapsed 'Add Handler to New Timer
tmr.SynchronizingObject = frmNew 'Synchronize Timer to newly created form
tmr.Interval = 1000 * multiplier
tmr.Enabled = True
tmr.Start()
End Sub
Public Sub Timer_Elapsed(sender As Object, e As ElapsedEventArgs)
Dim tmr As System.Timers.Timer = DirectCast(sender, System.Timers.Timer)
tmr.Stop() 'Stop Timer
DirectCast(tmr.SynchronizingObject, Form).Close() 'Get Form Timer was synchronized with and close it
tmr.SynchronizingObject = Nothing 'Remove Form reference from timer
RemoveHandler tmr.Elapsed, AddressOf Timer_Elapsed 'Remove Handler from Timer
End Sub