Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Global events for your application

0.00/5 (No votes)
22 Aug 2008 1  
How to use events through your application for multiple receivers.

Introduction

Sometimes it is useful that any form in an application can receive an event of another task so that it can handle some specific tasks. For example, you have a database that contains your lookup values that are used by your combo boxes. Now, if you update this lookups, it would be nice that all open forms would update their combo boxes, too. But how do we handle this?

Background

As I searched for a solution for this problem, a Xing buddy named Sascha Kiefer gave me the hint of using some delegates (using C#...). But using delegates in VB.NETis not necessary, and after some more research, I had the solution with just a few lines of code.

Using the code

First of all, you need a class that contains your event and a procedure to raise the event.

Public Class GlobalEventing
    Public Shared Event SpecialEventRaised(ByVal sender As Object, _
           ByVal type As String, ByVal msg As String)

    Public Shared Sub SpecialEvent(ByVal sender As Object, _
           ByVal type As String, ByVal msg As String)
        RaiseEvent SpecialEventRaised(sender, type, msg)
    End Sub
End Class

Now, the easiest part is to raise the event ... just call the proc.

GlobalEventing.SpecialEvent(me, "my typ", "my message")

In your forms, you just add an object reference, an addhandler statement, and a addressof procedure to handle the event.

Public Class ChildForm
    Inherits System.Windows.Forms.Form
  Dim gEvent As GlobalEventing
  (...)

  Private Sub ChildForm_Load(ByVal sender As System.Object, _
          ByVal e As System.EventArgs) Handles MyBase.Load
      AddHandler gEvent.SpecialEventRaised, AddressOf SpecialEventFired
  End Sub

  Private Sub SpecialEventFired(ByVal sender As Object, _
              ByVal typ As String, ByVal msg As String)
    txtOutput.AppendText(Now().ToLocalTime.ToString & " received " & _
                         typ & " / " & msg & vbCrLf)
  End Sub
End Class

Example

In the example, you will find a small solution (in VS2003) with an MDI form. Each of the child forms can receive the event - just take a look.

Personal

Once more, I saw that often, complex questions can result in very easy answers - but you have to find them. Hope you can make use of this little bit of code... enjoy! Any remarks are welcome!

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