The ActiveX Control Implementation File
This file contains the main implementation code of our ActiveX control's ActiveX controller object. This is the object that defines an automation interface and implements the OLE automation-style properties, methods and events.
Let's walk through the file and examine the interesting lines of code:
unit ButtonImpl1;
interface
uses Windows, ActiveX, Classes, Controls, Graphics, Menus, Forms, StdCtrls, ComServ, StdVCL, AXCtrls, ButtonXControlLib;
The ActiveX unit is the unit that defines all the system interfaces and data types. It's like the OLE2 unit in Delphi 2, except that it's implemented using the new language features. The OLE2 unit is still around for compatibility with older code, but any new ActiveX code you write should be written using ActiveX.
AXCtrls defines the Delphi ActiveX class hierarchy, also called DAX.
The ButtonXControlLib unit is the Pascal-language version of the server's type library. It defines all the interfaces that are available to any object in the server. Normally you would never edit this file, since it is regenerated from the type library every time you edit and save the type library. Instead, you should edit the type library directly using Delphi's Type Library Editor.
type TButtonX = class(TActiveXControl, IButtonX)
This clause defines an object type, TButtonX, that will be used to implement the controller object. TActiveXControl is the base class of all ActiveX controls and is implemented in the AXCtrls unit. The statement also says that the class implements IButtonX, which is the control's automation interface defined in the type library.
private { Private declarations }
FDelphiControl: TButton;
This private member points to the VCL control. It gets initialized in the InitializeControl method, below. In code that appears below, this member is used to get and set properties, call methods, and do other operations on the VCL object.
FEvents: IButtonXEvents;
This is a pointer to the container's event sink. IButtonXEvents is a dispinterface, not a dual interface, so what is stored is really an IDispatch pointer. This value gets set when the EventSinkChanged method is called, when the control is inserted or removed from a container. FEventSink can be nil at various points in your program's execution, so always be aware of this. In fact, your control could be inserted into a container that cares nothing about events, so FEventSink could be nil all the time.
Note that while the DAX class library supports multicast events, it is far easier to write your control to fire unicast events. This works fine for ActiveX controls, where the control is likely to fire events only to its container.
procedure ClickEvent(Sender: TObject);
procedure KeyPressEvent(Sender: TObject; var Key: Char);
These are declarations for the event handler proxies. I'll discuss these below, where they are implemented.
protected
{ Protected declarations }
procedure InitializeControl; override;
procedure EventSinkChanged(const EventSink: IUnknown); override;
procedure DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage); override;
The preceding three methods declare implementations of three overridable virtual methods. These are discussed below.
function Get_Cancel: WordBool; safecall;
function Get_Caption: WideString; safecall;
function Get_Cursor: Smallint; safecall;
function Get_Default: WordBool; safecall;
function Get_DragCursor: Smallint; safecall;
function Get_DragMode: TxDragMode; safecall;
function Get_Enabled: WordBool; safecall;
function Get_Font: Font; safecall;
function Get_ModalResult: Integer; safecall;
function Get_Visible: WordBool; safecall;
These methods are property getter methods for the control. These methods come from the IButtonX interface. Note that all these automation methods are declared using the safecall calling convention. Safecall is the ObjectPascal convention used for declaring dual interface compatible automation methods. Safecall guarantees that if an exception is thrown it will be caught and returned as an OLE error, following OLE calling conventions. It also copies the return value into a return parameter slot, which is declared as an out parameter in the type library.
procedure Click; safecall;
This method is the only public method a TButton exposes that can be published via OLE automation. Most of TButton's public methods are internal to VCL's implementation or don't make sense for the object to provide for automation. For example, the SendToBack method, which is public in TButton's ancestor class TWinControl, is a method that should be provided by the container. This method is first declared in the IButtonX interface.
procedure Set_Cancel(Value: WordBool); safecall;
procedure Set_Caption(const Value: WideString); safecall;
procedure Set_Cursor(Value: Smallint); safecall;
procedure Set_Default(Value: WordBool); safecall;
procedure Set_DragCursor(Value: Smallint); safecall;
procedure Set_DragMode(Value: TxDragMode); safecall;
procedure Set_Enabled(Value: WordBool); safecall;
procedure Set_Font(const Value: Font); safecall;
procedure Set_ModalResult(Value: Integer); safecall;
procedure Set_Visible(Value: WordBool); safecall;
These methods are the property setter methods for the control, and are also defined in the IButtonX interface. They each take a single parameter, which is the new value for the property.
end;
implementation
{ TButtonX }
procedure TButtonX.InitializeControl;
This method is called after the control is created, but before the control is shown or inserted into its container. The main purpose of this method is to establish the connection between the COM controller object and the VCL object. In the implementation of this virtual method, the controller gets a pointer to the VCL object, and then hooks its event proxies into the VCL object.
begin
FDelphiControl := Control as TButton;
Control is a property (of type TWinControl) declared in TActiveXControl, that is initialized before InitializeControl is called. Of course, it really points to a TButton control, since that's what we want this ActiveX control to implement. This line of code coerces the TWinControl pointer back into a TButton, and stores that pointer in this object.
FDelphiControl.OnClick := ClickEvent;
FDelphiControl.OnKeyPress := KeyPressEvent;
These lines bind the VCL events in the control to this object's event handler proxy methods. This ensures that when the VCL control fires events, this object will receive them. I'll describe the detail in the ClickEvent and KeyPressEvent implementations, but obviously the control will forward the event to its container, using the ActiveX event protocol.
Bug: The wizard should have generated code for the standard events, and should have bound OnKeyPress to TActiveXControl.StdKeyPressEvent, and OnClick to StdClickEvent. By the time you read this, a fix may be available for the wizard. end;
procedure TButtonX.EventSinkChanged(const EventSink: IUnknown);
begin
FEvents := EventSink as IButtonXEvents;
This code receives the event sink that the container provided, and remembers it in the FEvents member. FEvents will be used later to fire events to the object's container. IButtonXEvents is the control's event dispinterface, which is declared as the default source interface in the type library.
end;
procedure TButtonX.DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage);
begin
{ Define property pages here. Property pages are defined by calling DefinePropertyPage with
the class id of the page. For example, DefinePropertyPage(Class_ButtonXPage); }
This protected method starts with no actual implementation code. It provides you with a means of enumerating the property pages that you want shown for your control. Since your project initially has no property pages, this method is left blank, with instructions on how to fill it in. I'll come back to this topic later, when we discuss property pages.
end;
Implementing Property Get and Set Methods
The following are typical property getter and setter methods. All of these follow the same basic pattern: they're safecall OLE automation method implementations for property get and set calls. Since the only thing you have to do to set a property in Delphi is to assign the value, most of these methods look like the following two methods:
function TButtonX.Get_Cancel: WordBool;
begin
Result := FDelphiControl.Cancel;
end;
procedure TButtonX.Set_Cancel(Value: WordBool);
begin
FDelphiControl.Cancel := Value;
end;
There are a number of cases where the property accessor code may be more complicated. When the data type of the property is an integer-derived type, the value parameter in a setter function is passed in as a SmallInt. Your code needs to typecast this number into the appropriate Pascal type type before assigning it to a Pascal property. For example, the Cursor property is of type TCursor, which is declared:
type TCursor = -32768..32767;
The implementation of Cursor's getters and setters look like this: function TButtonX.Get_Cursor: Smallint;
begin
Result := Smallint(FDelphiControl.Cursor);
end;
procedure TButtonX.Set_Cursor(Value: Smallint);
begin
FDelphiControl.Cursor := TCursor(Value);
end;
ActiveX string properties (BSTRs) are compatible with Delphi's WideString type, and must be used even if the VCL component exposes a property as an AnsiString. You can do this by converting the AnsiString value to a WideString in the getter function, and vice versa in the setter function. (in this example, remember the TCaption type is a synonym for String).
function TButtonX.Get_Caption: WideString;
begin
Result := WideString(FDelphiControl.Caption);
end;
procedure TButtonX.Set_Caption(const Value: WideString);
begin
FDelphiControl.Caption := TCaption(Value);
end;
Another interesting case concerns properties that have complex OLE types, such as fonts, pictures, and string lists. Since a font is a separate object that has a dispatch interface, it can be modified independently of the control, and the control needs to refresh appropriately when this happens. For example, you could say in VB:
myFont = control.Font
myFont.Facename = 'Arial'
In this case, the control needs to change its font to Arial and refresh the display. This necessitates that the Get_Font method should create and return an OLE object that can expose the properties of the font as OLE properties. Conversely, setting the VCL's property in the TFont variable should update the OLE font.
Fortunately, the DAX library provides builtin functions for handling these common types. The font property's getter and setter method implementations demonstrate the use of the GetOleFont and SetOleFont functions.
function TButtonX.Get_Font: Font;
begin
GetOleFont(FDelphiControl.Font, Result);
end;
procedure TButtonX.Set_Font(const Value: Font);
begin
SetOleFont(FDelphiControl.Font, Value);
end;
You'll notice that the ActiveX Control wizard does not generate a complete list of all the properties that TButton publishes to the Delphi form designer. The wizard has decided that the Height, HelpContext, Hint, Left, Name, ParentFont, ParentShowHint, PopupMenu, ShowHint, TabOrder, Tag, Top and Width properties should not be exposed to OLE automation, because they don't make sense for an ActiveX control. This can be because the container implements the behavior itself using extended properties (in the case of position and tabbing properties), because ActiveX containers do not implement the behavior (ParentFont, HelpContext and hints), or because the property type is not standard OLE property type (PopupMenu).
The TActiveXControl class also contributes a number of property accessors for the properties available to any TWinControl. These include the following properties: BackColor, Caption, Enabled, Font, ForeColor, HWnd, TabStop, and Text.
Implementing Methods
Passing on automation methods to the VCL control is fairly straightforward. Simply call the appropriate method in the VCL control that is kept in FDelphiControl. Methods that have parameters may need to be modified, but this control doesn't have any.
procedure TButtonX.Click;
begin
FDelphiControl.Click;
end;
Event Handling
The following two methods demonstrate how a Delphi-style event handler forwards an event to the object's container. The event handlers are connected to the VCL control in the InitializeObject method, above.
procedure TButtonX.ClickEvent(Sender: TObject);
begin
if
FEvents <> nil then
FEvents.OnClick;
This implementation simply passes on the event to the container's event sink, if it has been installed. FEvents was set in the EventSinkChanged method described above. FEvents is a dispinterface, which means it is really just an IDispatch pointer.
Historical note: When I first implemented this, FEvents was a Variant from Delphi 2 until the compiler folks had dispinterfaces working properly. Calling a method on a dispinterface works just like calling a method on a Variant that contains an IDispatch pointer, but there are two key differences. The first is performance: calling through a dispinterface binds the method's dispid at compile-time, eliminating the sometimes costly GetDispIDsOfNames call.
The second difference is that while ActiveX control containers expose their event sinks using an IDispatch pointer, in this case the IDispatch implementation is not required to implement GetDispIDsOfNames at all! It turns out that some containers do implement this code, but most do not. If you want your event firing to work in all containers, you must use dispinterfaces to fire the events.
end;
procedure TButtonX.KeyPressEvent(Sender: TObject; var Key: Char);
var TempKey: Smallint;
begin
In a this case, the parameters expected for OLE events are not the same as for the Delphi events. In these cases the event handler proxy may need to massage the event's parameters before firing the event to the container. In this case, the OnKeyPress event passes a pointer to a SmallInt to the container, but the Delphi control passes a pointer to a Char to the event handler.
OLE events don't have a Sender parameter, so that parameter is dropped before passing on the event to the parent.
TempKey := Smallint(Key);
if FEvents <> nil then
FEvents.OnKeyPress(TempKey);
Key := Char(TempKey);
end;
TActiveXControl contributes handlers for common events like Click, DblClick, KeyDown, KeyPress, KeyUp, MouseDown, MouseMove, and MouseUp.
initialization
TActiveXControlFactory.Create(
ComServer, TButtonX, TButton, Class_ButtonX, 1, '', 0);
This line of code, which gets executed when the library is loaded, creates the class factory (based on the class, TActiveXControlFactory) for the control.
ComServer is a global variable that represents the library itself. Among other things, the ComServer contains a list of all the factories that have been created in the library. The other parameters to the factory are:
TButtonX - the ActiveX implementation class defined above
TButton - the VCL control class
Class_ButtonX - the ClassID of the object. This GUID is imported from the ButtonXControlLib unit, generated from the type library.
ToolbarBitmapID - this is a resource identifier of a bitmap resource. The wizard generates a bitmap resource for each control, based on the control's registered icon. ActiveX containers extract this bitmap to show on their control palettes.
LicenseString - This is blank because we didn't select
MiscControl flags - these are a combination of OLEMISC_* values that you can use to request special container behavior. DAX always adds the following flags to any VCL-derived control: OLEMISC_RECOMPOSEONRESIZE, OLEMISC_CANTLINKINSIDE, OLEMISC_INSIDEOUT, OLEMISC_ACTIVATEWHENVISIBLE, OLEMISC_SETCLIENTSITEFIRST
end.
The Type Library
The ActiveX type library is a binary file containing the meta-data for each of the controls listed in an ActiveX library. It describes the objects in the library, the properties, methods and events and other interfaces available to each control, and the user-defined data types used for these. In addition to containing symbol names and type information, a type library contains a variety of other information, including human- readable descriptive text, a reference to a help file and GUIDs for each of these items. When you compile an ActiveX library, the type library gets copied into the DLL as a resource, where it can be loaded by any interested client program.
The ActiveX wizards generate a type library for you when you first create the ActiveX Control from a Delphi VCL, and stores the type library in a .TLB file. This library defines all the properties and methods for your ActiveX control.
For any properties or parameters that convert to OLE compatible types, the wizard generates properties and parameters using those OLE types. When your control contains enumeration properties or parameters, the wizard generates a type declaration for that enumeration in the type library. In the case where the data type is a TFont, TPicture, or TStrings, the wizard assigns the property or parameter an IFont, IPicture or IStrings type and generates adapter code to convert between the data types.
If your VCL control contains properties or parameters that aren't standard or adaptable, generally records or non-COM object types, the wizard will skip that data item. This doesn't mean that the property doesn't exist, only that you won't be able to access it through a COM interface.
The Pascal Version of the Type Library
unit ButtonXControlLib;
{ This file represents the pascal declarations
of a type library and will be written during each import or
refresh of the type library editor. Changes to this file will
be discarded during the refresh process. }
{ ButtonXControlLib Library }
{ Version 1.0 }
interface
uses Windows, ActiveX, Classes, Graphics, OleCtrls, StdVCL;
const LIBID_ButtonXControlLib: TGUID = '{B12863C0-A9EA-11D0-A6DF-444553540000}';
const
{ TxDragMode }
dmManual = 0;
dmAutomatic = 1;
{ TxMouseButton }
mbLeft = 0;
mbRight = 1;
mbMiddle = 2;
const
{ Component class GUIDs }
Class_ButtonX: TGUID = '{B12863C3-A9EA-11D0-A6DF-444553540000}';
type
{ Forward declarations }
IButtonX = interface;
DButtonX_ = dispinterface;
IButtonXEvents = dispinterface;
ButtonX = IButtonX;
TxDragMode = TOleEnum;
TxMouseButton = TOleEnum;
{ Dispatch interface for ButtonX Control }
IButtonX = interface(IDispatch)
['{B12863C1-A9EA-11D0-A6DF-444553540000}']
This is the control's main (dual) automation interface. The controller object's class will implement all these methods.
procedure Click; safecall;
function Get_Cancel: WordBool; safecall;
procedure Set_Cancel(Value:WordBool); safecall;
function Get_Caption: WideString; safecall;
procedure Set_Caption(constValue: WideString); safecall;
function Get_Default: WordBool; safecall;
procedure Set_Default(Value: WordBool); safecall;
function Get_DragCursor: Smallint; safecall;
procedure Set_DragCursor(Value: Smallint); safecall;
function Get_DragMode: TxDragMode; safecall;
procedure Set_DragMode(Value: TxDragMode); safecall;
function Get_Enabled: WordBool; safecall;
procedure Set_Enabled(Value: WordBool); safecall;
function Get_Font: Font; safecall;
procedure Set_Font(const Value: Font); safecall;
function Get_ModalResult: Integer; safecall;
procedure Set_ModalResult(Value: Integer); safecall;
function Get_Visible: WordBool; safecall;
procedure Set_Visible(Value: WordBool); safecall;
function Get_Cursor: Smallint; safecall;
procedure Set_Cursor(Value: Smallint); safecall;
property Cancel: WordBool read Get_Cancel write Set_Cancel;
property Caption: WideString read Get_Caption write Set_Caption;
property Default: WordBool read Get_Default write Set_Default;
property DragCursor: Smallint read Get_DragCursor write Set_DragCursor;
property DragMode: TxDragMode read Get_DragMode write Set_DragMode;
property Enabled: WordBool read Get_Enabled write Set_Enabled;
property Font: Font read Get_Font write Set_Font;
property ModalResult: Integer read Get_ModalResult write Set_ModalResult;
property Visible: WordBool read Get_Visible write Set_Visible;
property Cursor: Smallint read Get_Cursor write Set_Cursor;
end;
{ DispInterface declaration for Dual Interface IButtonX }
DButtonX_ = dispinterface ['{B12863C1-A9EA-11D0-A6DF-444553540000}']
This is the dispinterface version of the dual interface above.
procedure Click; dispid 1;
property Cancel: WordBool dispid 2;
property Caption: WideString dispid 3;
property Default: WordBool dispid 4;
property DragCursor: Smallint dispid 5;
property DragMode: TxDragMode dispid 6;
property Enabled: WordBool dispid 7;
property Font: Font dispid 8;
property ModalResult: Integer dispid 9;
property Visible: WordBool dispid 10;
property Cursor: Smallint dispid 11;
end;
{ Events interface for ButtonX Control }
IButtonXEvents = dispinterface
['{B12863C2-A9EA-11D0-A6DF-444553540000}']
This is the events dispinterface for the control. The control can fire these events to its container if the container installs an event sink.
procedure OnClick; dispid 1;
procedure OnKeyPress(var Key: Smallint); dispid 2;
end;
[Note: This file also includes declarations for TButtonX, which is the VCL class generated when you import the ButtonX control back into Delphi. For brevity's sake, I've deleted this from this listing.]
implementation
end.