VB.Net一次关闭两个表单

时间:2016-01-11 13:02:43

标签: vb.net winforms

有点新的视觉模式,需要让这个简单的事情为我的课程项目工作。

期望的结果是当用户尝试退出Form2时,另一个表单(FormCheck)将打开,询问用户是否确定要离开,如果他们选择是,则Form2和FormCheck将关闭,Form1将打开。但是,当我尝试这样做时,FormCheck将关闭,Form1将打开,但Form2将在Form1后面保持打开状态。

这是我的代码:

Private Sub btnYes_Click(sender As Object, e As EventArgs) Handles btnYes.Click
        Dim NewForm As Form1
        NewForm = New Form1
        NewForm.Show()
        NewForm = Nothing
        Me.Close()
        Form2.Close()

正如我所说的那样,如果答案尽可能基本,那么这将有所帮助。 提前谢谢!

3 个答案:

答案 0 :(得分:0)

您必须找到现有的Form2

'YOUR EXISTING CODE HERE
For Each frm as Form in Application.OpenForms
    If frm.Name="Form2"
        frm.Close()
    End If
Next
'CLOSE THIS FORM HERE

您应该在关闭当前表单之前运行此代码。

答案 1 :(得分:0)

您可以通过在Form2中添加一个属性来执行此操作,该属性用于指示用户是单击是还是否。根据他的回答,你可以关闭Form1。无论如何,一旦用户点击是或否,Form2将被关闭。

Public Partial Class Form1
    Inherits Form
    Public Sub New()
        InitializeComponent()
    End Sub

    Private Sub button1_Click(sender As Object, e As EventArgs)
        Dim form2 As New Form2()
        form2.ShowDialog()

        If form2.IsExitRequired Then
            Me.Close()
        End If
    End Sub
End Class

Public Partial Class Form2
    Inherits Form
    Public Sub New()
        InitializeComponent()
    End Sub

    Public Property IsExitRequired() As Boolean
        Get
            Return m_IsExitRequired
        End Get
        Private Set
            m_IsExitRequired = Value
        End Set
    End Property
    Private m_IsExitRequired As Boolean

    Private Sub yesButton_Click(sender As Object, e As EventArgs)
        IsExitRequired = True
        Close()
    End Sub

    Private Sub noButton_Click(sender As Object, e As EventArgs)
        IsExitRequired = False
        Close()
    End Sub
End Class

答案 2 :(得分:0)

在关闭当前表单之前,您必须先关闭另一个表单。

Form2.Close() 
Me.Close()