This may not be the best way, but I thought it was a pretty cool way, so am sharing it.
Problem: I have a dynamic number instances of a specific form that are MDIChildren. There will be other kinds of MDIChildren forms as well. When the last, and only the last, instance of the specific form closes I want to do “something”.
Solution: Hook the FormClosed Event. In that event use Linq to Objects, Aggregate and Count() to get the current count of just that specific form type and if we’re closing the last form, do the “something.”
Hooking up the event when creating a new instance of the form in question (in the MDI Parent):
Dim ex As New ExampleForm
ex.MdiParent = Me
ex.Show()
AddHandler ex.FormClosed, AddressOf ExampleFormFormClosed
An instance of the given form closes, firing the FormClosed event (in the MDI Parent):
We’ll use Linq to Objects, filter by the form name and get the Count. if the count is 1, then we’re closing the last instance of that form
Private Sub ExampleFormFormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs)
RemoveHandler DirectCast(sender, Form).FormClosed, AddressOf ExampleFormFormClosed
Dim EXForms As Integer = Aggregate a In Me.MdiChildren Where a.Name = "ExampleForm" Into Count()
If EXForms <= 1 Then 'When closing the last instance of the form, the count will still be 1
'Do the stuff you want to do when you close that last type of that MDIChild
End If
End Sub
Again, I’m a Linq noob, but I thought this pretty cool and wanted to capture it for the future… If there’s a better way, please feel free to comment. :)
No comments:
Post a Comment
NOTE: Anonymous Commenting has been turned off for a while... The comment spammers are just killing me...
ALL comments are moderated. I will review every comment before it will appear on the blog.
Your comment WILL NOT APPEAR UNTIL I approve it. This may take some hours...
I reserve, and will use, the right to not approve ANY comment for ANY reason. I will not usually, but if it's off topic, spam (or even close to spam-like), inflammatory, mean, etc, etc, well... then...
Please see my comment policy for more information if you are interested.
Thanks,
Greg
PS. I am proactively moderating comments. Your comment WILL NOT APPEAR UNTIL I approve it. This may take some hours...