我试图一次只保留一个活跃的孩子。我想在MDI表格中打开任何孩子时处理其他孩子。 我没有运气就尝试了许多方法。有一个单独的类函数来做脏工作会很好。任何帮助将受到高度赞赏。 以下是示例代码表类:
Imports System.Reflection
Class closeHelper
Public Shared Sub HideAllForms()
Dim currentAssembly As Assembly = Assembly.GetExecutingAssembly()
Dim count As Integer = Application.OpenForms.Count
For i As Integer = 0 To count - 1 Step +1
Dim f As Form = Application.OpenForms(i)
If f.[GetType]().Assembly Is currentAssembly AndAlso f.Name <> "frmMDI" Then 'Here 'frmMDI' is the name of mdiform.
f.Close()
End If
Next
End Sub
End Class
答案 0 :(得分:2)
在删除或执行将修改集合的操作时,应始终使用反向循环。
For i As Integer = (count - 1) To 0 Step -1
使用正向循环来拍摄此照片(3
项的集合):
如您所见,最后一个将抛出IndexOutOfRangeException
。
答案 1 :(得分:1)
通常不应该在迭代它的同一循环中修改集合。
关闭表单后,它不再是OpenForms集合的一部分,因此您可以跳过其他所有表单。然后它失败了一半,因为索引关闭了。例如,假设您有3个表单。在索引0处,您将关闭表单#1,将所有打开的表单移动1.在索引1处您有表单#3(因为#2现在低于0)并且您将其关闭。然后尝试关闭索引#3处的表单,但它不存在,并且您的集合中现在只有1个项目(因此一个表单保持打开状态,您也会获得异常)。
相反,将OpenForms复制到Form数组中,并执行相同的过程。
Public Shared Sub HideAllForms()
Dim currentAssembly As Assembly = Assembly.GetExecutingAssembly()
'remember which forms were open, we don't want to mess our indexes
Dim forms As New List(Of Form)
For Each frm in Application.OpenForms
forms.Add(frm)
Next
'iterate over all forms which were open at the start of this method
For Each f As Form in forms
If f.[GetType]().Assembly Is currentAssembly AndAlso f.Name <> "HOME" Then 'Here 'HOME' is the name of mdiform.
f.Close()
End If
Next
End Sub
答案 2 :(得分:1)
Private Sub ToolStrip1_ItemClicked(sender As System.Object, e As System.Windows.Forms.ToolStripItemClickedEventArgs) Handles ToolStrip.ItemClicked
Dim ToolStripClickedItem As String = e.ClickedItem.Name
Select Case ToolStripClickedItem
Case "ToolStripButtonEmployee"
For Each f As Form In Application.OpenForms
If TypeOf f Is frmEmployee Then
f.Activate()
Return
End If
Next
Dim childEmployee As New frmEmployee
childEmployee.MdiParent = Me
childEmployee.StartPosition = FormStartPosition.CenterScreen
childEmployee.Show()
End sub
我是从ToolStripButtonEmployee.ToolStrip1_ItemClicked
事件
答案 3 :(得分:0)
嗯,下面的代码对我有用。唯一的问题是,如果我再次单击按钮打开当前表单,它似乎重新打开表单。我再试几次了。
Public Shared Sub HideAllForms()
Dim currentAssembly As Assembly = Assembly.GetExecutingAssembly()
Dim count As Integer = Application.OpenForms.Count
For i As Integer = (count - 1) To 0 Step -1
Dim f As Form = Application.OpenForms(i)
If f.[GetType]().Assembly Is currentAssembly AndAlso f.Name <> "HOME" Then 'Here 'HOME' is the name of mdiform.
f.Close()
End If
Next
End Sub