VB.NET在一段时间后创建并关闭表单

时间:2014-09-11 02:21:44

标签: vb.net forms timer

几秒钟之后,我可以轻松地关闭表格;但是,当我想要一个接一个地关闭许多表格时,他们会创建相同的序列"&#34 ;;我无法弄清楚: 主要表格代码如下:

    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

我启动了一个计时器,但是我尝试关闭表单的所有方法都与它们创建的顺序相同;不成功; 帮助赞赏;并提前感谢。

1 个答案:

答案 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