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!