Reputation: 978
In every form of a project I am working on, there are some FlowLayoutPanel
s which contain three Label
s. Those Label
s work as Minimize, Maximize and Close form buttons. In other words an own Form Control Box.
In every form there is a Private Sub
like the one below, which is called by custom buttons events:
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
In order to avoid to repeat this part of code in every form, I thought it would be better to place it once into a module. I have tried to convert this part of code as it should be in a module, but with no success. When I click on any of the three Label
s, I get this message:
System.InvalidOperationException: 'Collection was modified; enumeration operation may not execute.'
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
Upvotes: 0
Views: 279
Reputation: 25351
The original code that you had in each form is good. You don't need the loop and other modifications that you added to it.
All you needed to do is replace the Me
with _Label.FindForm()
, and of course make it Public
like you did:
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
Upvotes: 2