Click here to Skip to main content
15,894,955 members
Articles / Desktop Programming / Windows Forms

Application Event Handler for WinForms

Rate me:
Please Sign up or sign in to vote.
4.77/5 (16 votes)
11 Nov 20046 min read 157.1K   1.9K   83  
In this article, you will get a walkthrough of creating an Application Event Handler Component (AEHC) for any WinForms application in .NET.
Imports System.Windows.Forms
Imports System.ComponentModel

Public Class ApplicationEventHandler
    Public Event FormLoaded(ByRef sender As Form)
    Public Event FormUnloaded()

    'Shared Readonly FormsCollection Property 
    'Use this property to access your loaded forms
    Public Shared ReadOnly Property FormsCollection() As ArrayList
        Get
            Return FormMessageFilter.frmCollection
        End Get
    End Property

    'Use this property to initialize AEH
    'and attaches the FormFilter to the application
    <Description("Use this function to add the Form Filter to the application")> Public Sub Init()
        'Declare an Instance of our Custom Form Filter
        Dim MyFilter As New FormMessageFilter

        'Attach the procedures to handle the events of MyFilter
        AddHandler MyFilter.FormFound, AddressOf pFormLoaded
        AddHandler MyFilter.FormUnload, AddressOf pFormUnLoaded

        'Adds Forms Message Filter to the Application
        Application.AddMessageFilter(MyFilter)
    End Sub

    'pFormLoaded method is called whenever any form is loaded in the application
    'and raises FormLoaded Event to provide notification to the application
    'Use AppEventHandlerArgs.FormsCollection Property to control the forms
    Private Sub pFormLoaded(ByRef CurForm As Form)
        RaiseEvent FormLoaded(CurForm)
    End Sub

    'pFormUnLoaded method is called whenever any form is unloaded in the application
    'and raises FormUnLoaded Event to provide notification to the application
    'Use AppEventHandlerArgs.FormsCollection Property to control the forms
    Private Sub pFormUnLoaded()
        RaiseEvent FormUnloaded()
    End Sub
End Class

'Custom Filter Message Class for filtering the messages and 
'store the form in the FormArrayList
Friend Class FormMessageFilter
    Implements IMessageFilter

    'Shared Forms Collection for adding and deleting forms
    'in the collection
    Friend Shared frmCollection As New ArrayList

    'Whenever any form is loaded FormFound Event is raised
    Public Event FormFound(ByRef sender As Form)
    'Whenever any form is unloaded FormFound Event is raised
    Public Event FormUnload()

    Dim frID As Integer
    Dim ShowCount As Boolean
    Dim c As Integer
    Dim k As Integer


    'This method is called whenever and message is pumped in the message queue
    'And is responsible for Filtering the message
    Public Function PreFilterMessage(ByRef m As System.Windows.Forms.Message) As Boolean Implements System.Windows.Forms.IMessageFilter.PreFilterMessage

        If m.Msg = &HF Then
            k = k + 1
            If Not (Form.ActiveForm) Is Nothing Then
                'Holds the Current Active Form in local variable
                Dim curForm As Form = Form.ActiveForm

                'Search the forms in the Forms Collection
                'before adding them in the Form collection
                'to prevent duplication of forms in the collection
                If Not (Search(curForm, frmCollection)) Then
                    Console.WriteLine(m.Msg & " : " & k)
                    k = 0
                    c = c + 1
                    frID = m.Msg
                    'Adds the Form in the Form collection
                    frmCollection.Add(curForm)
                    'Attaches Closed event handler for the Current Form
                    AddHandler curForm.Closed, AddressOf MyForm_Closed

                    'Raises FormFound Event for AEH to trap
                    RaiseEvent FormFound(curForm)
                End If

            End If
        End If

        'Must return false to release the Message
        Return False


    End Function

    'Private Function GetFormMessage(ByVal ID As Integer) As Integer

    '    If Not (Form.ActiveForm) Is Nothing Then
    '        ChkFr = False
    '        Return ID
    '    Else
    '        Return -1
    '    End If
    'End Function

    'MyForm_Closed is called when a form is closed
    'This method removes the unloaded form from the forms collection
    Private Sub MyForm_Closed(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim k, j As Integer

        'Removes the forms which are disposed (Form.Dispose) rather being closed(Form.Close) 
        For i As Integer = 0 To frmCollection.Count - 1
            j = i - k

            If j > (frmCollection.Count - 1) Then
                Exit For
            End If

            'Checks the IsDisposed Property of the Form in the Forms Collection
            'When this property returns true, the control is disposed of and can
            'no longer be referenced as a valid Windows forms. 
            If frmCollection(j).IsDisposed = True Then
                frmCollection.Remove(frmCollection(j))
                k = k + 1
            End If
        Next

        'Removes the form which raised the close event
        If Not (sender) Is Nothing Then frmCollection.Remove(sender)

        'Raises the FormUnload for sending notification to AEH to trap
        RaiseEvent FormUnload()

    End Sub

    'Search Method searches fr(form) in the forms collection (frmArray)
    Private Function Search(ByVal fr As Form, ByVal frmArray As ArrayList) As Boolean
        Dim k As Integer
        Dim fr1 As Form

        For Each fr1 In frmArray

            If Not (fr) Is Nothing Then
                k = k + 1
                If fr.Equals(fr1) Then Return True
            End If
        Next

        If ShowCount Then MsgBox(k)
        Return False
    End Function

End Class

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
India India
Saurabh Verma works as an Architect, possessing over 10 years designing and developing software and currently assists product companies to scale and writing flexible software. He has vast experience in designing Web 2.0 solutions using Microsoft Technologies; WF, WCF and AJAX.ASP.NET, and practicing AGILE Methodologies and Domain Driven Design for the implementation. He likes to perform superbike stunts in his free time. Smile | :)

He has been awarded Microsoft Most Valuable Professional, MCSD.NET, MCAD.NET, MCDBA and Microsoft Web Rock Star 2007.

He maintains his blog at http://www.domaindrivendesign.info for all the aspiring architects and developers.

You can reach him at saurabhdotnet@hotmail.com

Comments and Discussions