在我正在处理的每个项目形式中,有一些FlowLayoutPanel
包含三个Label
s。这些Label
用作最小化,最大化和关闭表单按钮。换句话说,一个自己的表格控制框。
在每种形式中都有一个Private Sub
,如下所示,由自定义按钮事件调用:
Private Sub AllForms_CustomControlBox_Controls_Click(sender As Object, e As EventArgs)
Dim _Label = DirectCast(sender, Control)
If _Label.Name = "Custom_MinimizeForm_Label" Then
Me.WindowState = FormWindowState.Minimized
ElseIf _Label.Name = "Custom_MaximizeForm_Label" Then
If Me.WindowState = FormWindowState.Normal Then
Me.WindowState = FormWindowState.Maximized
ElseIf Me.WindowState = FormWindowState.Maximized Then
Me.WindowState = FormWindowState.Normal
End If
ElseIf _Label.Name = "Custom_CloseForm_Label" Then
Me.Close()
End If
End Sub
为了避免在每种形式中重复这部分代码,我认为最好将它放入模块中一次。我试图将这部分代码转换为应该在模块中,但没有成功。当我点击三个Label
中的任何一个时,我收到此消息:
System.InvalidOperationException:'收集已修改;枚举操作可能无法执行。'
Public Sub AllForms_CustomControlBox_Controls_Click(sender As Object, e As EventArgs)
For Each _Form As Form In My.Application.OpenForms.OfType(Of Form)()
For Each _FlowLayoutPanel As Control In _Form.Controls.OfType(Of FlowLayoutPanel)()
For Each _Label As Control In _FlowLayoutPanel.Controls.OfType(Of Label)()
If _Label.Name = "Custom_MinimizeForm_Label" Then
_Form.WindowState = FormWindowState.Minimized
ElseIf _Label.Name = "Custom_MaximizeForm_Label" Then
If _Form.WindowState = FormWindowState.Normal Then
_Form.WindowState = FormWindowState.Maximized
ElseIf _Form.WindowState = FormWindowState.Maximized Then
_Form.WindowState = FormWindowState.Normal
End If
ElseIf _Label.Name = "Custom_CloseForm_Label" Then
_Form.Close()
End If
Next
Next
Next
End Sub
答案 0 :(得分:2)
每种形式的原始代码都很好。您不需要添加循环和其他修改。
您需要做的只是将Me
替换为_Label.FindForm()
,当然可以像{I}一样将其Public
替换为:{/ p>
Public Sub AllForms_CustomControlBox_Controls_Click(sender As Object, e As EventArgs)
Dim _Label = DirectCast(sender, Control)
Dim _Form = _Label.FindForm()
If _Label.Name = "Custom_MinimizeForm_Label" Then
_Form.WindowState = FormWindowState.Minimized
ElseIf _Label.Name = "Custom_MaximizeForm_Label" Then
If _Form.WindowState = FormWindowState.Normal Then
_Form.WindowState = FormWindowState.Maximized
ElseIf Me.WindowState = FormWindowState.Maximized Then
_Form.WindowState = FormWindowState.Normal
End If
ElseIf _Label.Name = "Custom_CloseForm_Label" Then
_Form.Close()
End If
End Sub