这很简陋,但我想不通。
如果 form1 仍然打开,我想在 form2 关闭时以编程方式关闭 form1。Form2 由 form1 上的命令按钮打开。
窗体 1 上打开窗体 2 的代码是:
Dim frm As New form2
frm.Show()
当 Form2 关闭以关闭任何打开的 Form1 副本时,最好的方法是什么?
如果你想独立处理你的两个表单,你需要从第三个表单或类来监视它们。所以我的建议是在第三个类中创建它们,并将第二个表单的引用传递给第一个表单,以便它可以打开它。这边:
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
添加此引用以使其正常工作。
Imports System.Linq
If Application.OpenForms().OfType(Of Form1).Any Then
MsgBox("Form1 is open")
End If
假设您有 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