I just finished working on an app in Visual Basic 2005 Express (an update to BusyBox) and realized that the documentation on event handling in VB.Net is incomplete everywhere that I looked. As far as it goes, the existing Wiki entry is correct, but I couldn't implement that into working code.
The problem is that the wiki example just raises a message box. If you try to actually modify anything in your base class (e.g. - Form1) from the subroutine then you get exception errors.
The problem is that the event handler in VB2k5 runs in a separate thread and only the thread that the class object is running in can update its children. (Non-C programmer interpretation.)
There is a method to make it work. It involves a class called a delegate which contains a pointer for the event that can be used by the main thread. In otherwords, the delegate can look at the event handler thread and update the main program when there is a change.
The following code performs this function.
In the header, the Media Center object is referenced with the WithEvents modifier as in the original example. The delegate creating subroutine RelayEvent and its instance _RelayEvent are created with the three string parameters for the MediaCenter event.
Imports MediaCenter
Public Class MainForm
Dim WithEvents MC As MediaCenter.MCAutomation
Private _RelayEvent As RelayEvent
Delegate Sub RelayEvent(ByVal EventData1 As String, ByVal EventData2 As String, ByVal EventData3 As String)
...
A subroutine is written in the form MainForm (or Form1 or whatever) that is activated by the event handler task (via the delgate RelayEvent) when it receives an event from the MediaCenter object/program. This task is then used to update any information in the regular part of the program (main thread.)
Private Sub MyRelayEvent(ByVal EventData1 As String, ByVal EventData2 As String, ByVal EventData3 As String)
lbParam1.Text = EventData1
lbParam2.Text = Trim(EventData2)
lbParam3.Text = EventData3
Application.DoEvents()
End SubThe event handling task has to be modified slightly from the wiki example to tell it to use the delegate. To do this, in the event handler _RelayEvent is assigned as the delegate pointer (using the RelayEvent routine) referencing the subroutine MyRelayEvent over on the main thread. Then the BeginInvoke method is used to call MyRelayEvent via the delegate pointer.
Public Sub MC_FireMJEvent(ByVal s0 As String, ByVal s1 As String, ByVal s2 As String) Handles MC.FireMJEvent
_RelayEvent = New RelayEvent(AddressOf MyRelayEvent)
BeginInvoke(_RelayEvent, s0, s1, s2)
End SubThis will allow events to correctly update items in VB.Net. As an aside, the same MediaCenter object, MC, can be used for all of the other method and property calls. You do not need to create a separate one for accessing the other stuff in your program.