
WithEvents And Handles Clause Requires Form Us To Declare The Object Variable And The Event Handler As We Write Our Code, So Linkage Is Created Upon Compilation. On The Other Hand, With AddHandler And RemoveHandler, Linkage Is Created And Removed At Runtime, Which Is More Flexible.Let's Assume That We Want To Load Several MDI Child Forms, Allowing Each Of Them To Be Loaded Only Once, And Of Course To Know When One Of The Child Forms Is Closed. Since We Have Several Forms To Load We Would Like To Use The AddHandler And RemoveHandler Keywords So We Can Be Flexible And Write The Minimal Code We Can.Let's Get Dirty.1. In Each MDI Child Form We Have To Declare A Public Event.Public Event FormClosed(ByVal F As Form)2. In Each MDI Child Form We Have To Use The FormClosed Method Which Handles The MyBase.Closed Class And Raise The FormClosed Event.Private Sub Form1Closed(ByVal Sender As Object, ByVal E As System.EventArgs) Handles MyBase.Closed RaiseEvent FormClosed(Me)End Sub3. On Our MDI Form We Need To Declare Two Member Variables. The First's Of Type Form And The Second's Type Is ArrayList.Private Mf(0) As FormPrivate MsLoadedChildForms As New ArrayList4. We Need To Implement A Method The Will Search The MDI Child Forms That Are Loaded. We'll Also Use This Method When We Unload The MDI Child Forms.Private Function SearchChildForm(ByVal StrSearchForm As String, Optional ByVal IdxEventHandler As Long -1) As Long Dim I As Long 0 For I 0 To MsLoadedForms.Count - 1 If MsLoadedForms.Item(i) StrSearchForm Then Dim J As Long 0 For J Mf.GetLowerBound(0) To Mf.GetUpperBound(0) If Mf(j).Name StrSearchForm Then IdxEventHandler J Next J Return I End If Next Return -1End Function5. We Need To Implement A Method To Load The Mdi Child Forms And Use The SearchChildForm Method In Order Not To Load The Same Mdi Child Form Second Time.Private Sub LoadChildForms(ByVal F As Form) If Mf.GetUpperBound(0) 0 Then ReDim Preserve Mf(mf.GetUpperBound(0) 1) End If Mf(mf.GetUpperBound(0)) F If Not SearchChildForm(mf(mf.GetUpperBound(0)).Name()) 0 Then Mf(mf.GetUpperBound(0)).MdiParent Me AddHandler Mf(mf.GetUpperBound(0)).Closed, AddressOf UnloadChildForm Mf(mf.GetUpperBound(0)).Show() MsLoadedChildForms.Add(mf(mf.GetUpperBound(0)).Name) Else If Mf.GetUpperBound(0) 0 Then ReDim Preserve Mf(mf.GetUpperBound(0) - 1) End If End IfEnd Sub6. At Last We Need To Implement A Method To Take Out Our Mdi Child Form From The Array List So We Can Load It Again If We Want.Private Sub UnloadForm(ByVal Sender As System.Object, ByVal E As System.EventArgs) Dim I As Long Dim S As String Sender.GetType().Name Dim IndexForEventHandler -1 I SearchChildForm(s, IndexForEventHandler) If I 0 Then MsLoadedForms.RemoveAt(i) If IndexForEventHandler 0 Then RemoveHandler Mf(IndexForEventHandler).Closed, AddressOf UnloadForm Mf(IndexForEventHandler) Nothing End IfEnd Sub