Events from a module

From HashVB
Revision as of 14:40, 2 September 2005 by 81.76.105.240 (Talk)

Jump to: navigation, search

If you want to fire events in a COM object from a normal code module, you have a fairly major issue to work around.

The code module has no idea about the calling com object.

To get around this, you will need to pass a reference to the calling object to the function.
This can be done using a one of 2 methods:

  • Pass an object reference direct. This is only practical when you are calling the function direct
  • Pass a pointer to the object. This can work when calling it direct or when using windows callback. This has the advantage of not keeping an active reference to the object.

To Make this work, you will need to have a method in your class that the module calls and fires the event.

Friend Sub FireEvent(ByVal Param1 As Long)
  RaiseEvent EventName(Param1)
End Sub

This uses Friend instead of Public or Private as it will be accessible to your project but not to anything outside it.

You then need to pass the object reference to the module. If you are calling it direct, you can use this:

Public Sub ExternalProcedure(ByVal Caller As ClassName)
  'Do stuff here

  Caller.FireEvent 1
End Sub

Which can be called with:

ExternalProcedure Me

If you using it with a windows callback, most calls will allow you to pass a custom number to the callback. You can use this to pass a pointer of the object through to the module.

Public Sub CallbackProcedure(ByVal CallbackInfo As Long, ByVal CallerPtr As Long)
  'Do stuff here

Dim Tmp As Object
Dim Caller as ClassName

  CopyMemory Tmp, CallerPtr, 4
  Set Caller = Tmp
  CopyMemory Tmp, 0&, 4

  Caller.FireEvent 1
End Sub

You will need use an undocumented function called ObjPtr() to get the pointer to the object as follows:

WindowsFunction Param1, ObjPtr(Me)

Modularised Subclassing using interfaces and CopyMemory

Many people ask how to handle subclassing from within a class module. Well here's the answer: Modularised Subclassing using interfaces and CopyMemory.