Adding Events

From RAD Studio
Jump to: navigation, search

Go Up to Adding Additional Properties, Methods, and Events


The ActiveX control can fire events to its container in the same way that an automation object fires events to clients. This mechanism is described in Managing Events in Your Automation Object.

If the VCL control you are using as the basis of your ActiveX control has any published events, the wizards automatically add the necessary support for managing a list of client event sinks to your ActiveX wrapper class and define the outgoing dispinterface that clients must implement to respond to events.

You add events to this outgoing dispinterface. To add an event in the type library editor, select the event interface and click on the method icon. Then manually add the list of parameters you want to include using the parameter page.

Next, you must declare a method in your wrapper class that is of the same type as the event handler for the event in the underlying VCL control. This is not generated automatically, because Delphi does not know which event handler you are using:

 procedure KeyPressEvent(Sender: TObject; var Key: Char);

Implement this method to use the host application's event sink, which is stored in the wrapper class's FEvents member:

 procedure TButtonX.KeyPressEvent(Sender: TObject; var Key: Char);
 var
   TempKey: Smallint;
 begin
     TempKey := Smallint(Key); {cast to an OleAutomation compatible type }
     if FEvents <> nil then
       FEvents.OnKeyPress(TempKey)
     Key := Char(TempKey);
   end;
 void __fastcall TButtonXImpl::KeyPressEvent(TObject *Sender, char &Key)
 {
 short TempKey;
 TempKey = (short)Key;
 Fire_OnKeyPress(&TempKey);
 Key = (short)TempKey;
 };

Note: When firing events in an ActiveX control, you do not need to iterate through a list of event sinks because the control only has a single host application. This is simpler than the process for most Automation servers.

Finally, you must assign this event handler to the underlying VCL control, so that it is called when the event occurs. You make this assignment in the InitializeControl method:

 procedure TButtonX.InitializeControl;
 begin
   FDelphiControl := Control as TButton;
   FDelphiControl.OnClick := ClickEvent;
   FDelphiControl.OnKeyPress := KeyPressEvent;
 end;
 void InitializeControl()
 {
   m_VclCtl->OnClick = ClickEvent;
   m_VclCtl->OnKeyPress = KeyPressEvent;
 }

See Also