[AccessD] Demo sinking events in two places

jwcolby jwcolby at colbyconsulting.com
Thu Feb 12 09:10:39 CST 2009


Boy did I ever mess that one up.  IF you did not overwrite your original form frmDemoCtls then you 
SHOULD be able to:

* open frmDemoCtls FIRST
* Open frmDemoSinkingCommandButtonEvent
* Notice that the form pops up a message box telling you the name of that form plus the name of the 
command button back on frmDemoCtls
* Click the button on frmDemoCtls
* Notice a message box telling you the name of frmDemoCtls plus the name of the command control
* Close that message box.  Notice a message box telling you the name of 
frmDemoSinkingCommandButtonEvent plus the name of the control.

Whew.

So what happened?  frmDemoSinkingCommandButtonEvent has the following code inside of it:

Dim WithEvents cmd As CommandButton


Private Sub cmd_Click()
     MsgBox Me.Name & ": " & cmd.Name & ": Click event"
End Sub


Private Sub Form_Load()
     On Error Resume Next
     Set cmd = Forms!frmDemoCtls!Command15
     MsgBox cmd.Name
End Sub

Let's break that code down.

Dim WithEvents cmd As CommandButton

Here we dim a command button Withevents which tells VBA that this class will be sinking events for a 
command button named cmd.

Private Sub Form_Load()
     On Error Resume Next
     Set cmd = Forms!frmDemoCtls!Command15
     MsgBox cmd.Name
End Sub

The load event reaches over to frmDemoCtls and grabs a pointer to Command15, and SETs cmd = to that 
pointer.  It then pops up a message box telling you the name of the command button.  I placed the 
OnError line in there in case frmDemoCtls was not open yet.  The code will NOT run correctly if you 
load frmDemoCtls last.

Private Sub cmd_Click()
     MsgBox Me.Name & ": " & cmd.Name & ": Click event"
End Sub

And finally, we build an event sink in frmDemoSinkingCommandButtonEvent to run when the command 
button is clicked.

This might be a strange concept, sinking an event from an object in a form somewhere else but that 
is precisely what our clsCtlXXX is doing with combos, text boxes and eventually other control 
wrappers for objects such as radio buttons etc.  The important thing to understand in all this is 
that an event can be sunk in as many places as you want.  All you have to do is set it up. 
frmDemoSinkingCommandButtonEvent simly demonstrates how to sut up such a scenario.

In this lecture we have demonstrated that a form can sink an event for a control on another form. 
We have also demonstrated again that the form that contains the control gets code execution control 
first and runs its code.  Once it is finished, any other class that is also sinking that event gets 
control, in this case frmDemoSinkingCommandButtonEvent gets control.

Isn't this stuff FUN?

;-)

-- 
John W. Colby
www.ColbyConsulting.com



More information about the AccessD mailing list