vb.net代码,如果它是打开的,则关闭另一个表单

时间:2017-10-12 08:55:31

标签: vb.net

这是非常简陋的,但我无法弄明白。

如果form1仍然打开,我想在form2关闭时以编程方式关闭form1。 Form2上的命令按钮打开了Form2。

Form1上打开Form2的代码是:

Dim frm As New form2
frm.Show()

当Form2关闭以关闭所有打开的Form1的打开副本时,最好的方法是什么?

3 个答案:

答案 0 :(得分:1)

如果您想独立处理两个表单,则需要从第三个表单或类中查看它们。所以我的建议是在第三个类中创建它们,并将第二个表单的引用传递给第一个表单,以便它可以打开它。这样:

Public Class MyHelper

    Public Sub CreateForms()
        Dim form2 as New Form2()
        AddHandler form2.Closed, AddressOf Form2_OnClosed

        ‘ Create as many copies as you need
        Dim form1 as New Form1(form2)
        form1.Show()
    End Sub

    Protected Sub Form2_OnClosed(sender as object, e as EventArgs) 
        ‘ Same code for each form1 that has been created and opened.
        If (form1.IsOpen) Then form1.Close()
    End Sub

End Class


Public Class Form1

    Private _form2 as Form2

    Public Property IsOpen as Boolean = false

    Public Sub New(form2 as Form2)
        _form2 = form2
    End Sub

    Protected Sub MyButton_Click(sender as object, e as EventArgs) handles MyButton.Click
        ‘ You open your form here or wherever you want (even on the constructor)
        _form2.Show()
    End Sub

    Protected Sub Me_OnClosed(sender as object, e as EventArgs) handles Me.Closed
        Me.IsOpen = false
    End Sub

    Protected Sub Me_OnShown(sender as object, e as EventArgs) handles Me.Shown
        Me.IsOpen = true
    End Sub

End Class

答案 1 :(得分:1)

添加此引用以使其起作用。

Imports System.Linq

If Application.OpenForms().OfType(Of Form1).Any Then
   MsgBox("Form1 is open")
End If

答案 2 :(得分:-1)

假设您有 3 个表单,并且想在单击按钮时关闭另外两个表单

Private Sub EMPLEADOToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles EMPLEADOToolStripMenuItem.Click
    If Application.OpenForms().OfType(Of BUSCAR_INDEX).Any Then
        BUSCAR_INDEX.Close()
    ElseIf Application.OpenForms().OfType(Of MIEMBROS_INDEX).Any Then
        MIEMBROS_INDEX.Close()
    End If
    EMP_INDEX.Show()
    EMP_INDEX.EmpIDTextBox.Text = EmpIDTextBox.Text
End Sub