You are on page 1of 44

ActiveX Controls

Jim Fawcett CSE775 – Distributed Objects Spring 2004

ActiveX Controls
 

Controls Have a User Interface Controls know about events, properties, and automation

container invokes control's methods

Control Container

control sends event notification

ActiveX Control

properties are examined and modified

2

COM Architecture
adapted from Inside OLE, 2nd Edition, Kraig BrockSchmidt, Microsoft Press, 1995

COM Controls

OLE documents
in-place activation (visual editing) property pages

linking

events

embedding

property change notification

drag and drop

OLE automation

uniform data transfer

naming and binding (monikers)

connectable objects

persistent objects

structured storage

type information

component object model objects and interfaces, queryInterface

3

ActiveX Events

windows events:
– – – – – start in the raw system event queue get passed to the window manager to the handling window inserted into the window message queue get processed when the window gets to it in the queue

For ActiveX events:
– – – – interested observers register with the control for notification registration consists of sending a callback for an event handler when the event occurs the control “calls the observer back” the mechanisms to do this are based on connectable object interfaces.

4

   5 . Often the container also has “ambient” properties which the control is expected to adopt at start up. A control’s properties are accessed through an IDispatch interface.ActiveX Properties  Properties are persistent scalar values which can be read and written by a control’s container and/or program user. ActiveX controls support the notion of property pages which allow a control’s properties to be examined and modified in a standard way through a standard user interface.

DISPPARAMS structure . which don’t know anything about interface pointers.DISPID IDispatch Query Interf ace AddRef Release GetTy peInf oCount GetTy peInf o GetIDsOf Names Inv oke 6 . to make calls to COM components – – – – GetTypeInfoCount GetTypeInfo GetIDsOfNames invoke type info avail? returns pointer to type info get index of method to call call method through a dispatch table using .Automation .IDispatch Interface  Allows scripting languages.

arrow keys. both stock and custom Event callbacks. both stock and custom Property change notification On-demand rendering of a view Support for containers: OLE control and in-place activation Persistance support Windowless activation: an initialization optimization Object safety settings Drag and Drop support Graphical editing of its properties Support for arranging properties by category Default keyboard handling: tabbing. help 7 .ActiveX Control Functionality  A control is:  A control usually has: – – – – – – – – – – – – – A COM object: – A User Interface: – Createable Properties.

ActiveX Control in Container container invokes control's methods Control Container control sends event notification ActiveX Control properties are examined and modified 8 .

Relationship between ActiveX Control and its Container Container Interfaces Frame IOleInPlaceUI-Window Document IOleInPlaceUI-Window Control Interfaces Site IDispatch IAdviseSink IOleClientSite IOleControlSite IOleInPlaceActive-Object IViewObject Control IOleObject IOleControl 9 .

Invoking a Control’s Methods Container Interfaces Frame Document IDispatch interface Site Control 10 .

Interfaces for a Full ActiveX Control IOleInPlaceActiveObject Active object IOleInPlaceObject IOleObject IDataObject IViewObject2 IRunnableObject IOleCache2 ActiveX Control IPersistStorage IPersistStreamInit ISpecifyPropertyPages IConnectionPointContainer IConnectionPoint Connection point object IProvideClassInfo2 IDispatch IOleControl 11 .

Interfaces for an ActiveX Control Container Container Frame Object IOleInPlaceFrame Document Object IOleInPlaceUIWindow Control Site Object IOleInPlaceSite IOleClientSite IAdviseSink IOleControlSite IDispatch (ambient properties) IPropertyNotifySink Event Sink Object IDispatch (events) 12 .

Most Important ActiveX Interfaces Adapted from "ActiveX Controls Inside Out" Adam Denning Notification IAdviseSink IAdviseSink2 IMessageFilter IPropertyNotifySink IContinueCallback ActiveX Extensions IAuthenticate ICodeInstall IFillLockBytes IHlink IHlinkBrowseContext IHlinkFrame IHlinkSite IHlinkTarget IHttpNegotiate ILayoutStorage IProgressNotify IWinInetHttpInfo IWinInetInfo Programmability IDispatch IErrorLog dual Interfaces Component Object ActiveX Controls IUknown IClassFactory IClassFactory2 IMarshal IMalloc IStdMarshalInfo IExternalConnection IConnectionPoint IConnectionPointContainer ICatInformation ICatRegister IClientSecurity IMultiQI IServerSecurity IServiceProvider IOleControl IOleControlSite ISimpleFrameSite IFont IPicture IPersistStreaminit ISpecifyPropertyPages IPropertyPage IPropertyPage2 IPropertyPageSite IPerPropertyBrowsing IAdviseSinkEx IOleObjectWithSite IOleInPlaceObjectWindowless IOleInPlaceSiteEx IOleInPlaceSiteWindowless IPointerInactive IQuickActivate IViewObjectEx Naming and Binding IMoniker IBindCtx IRunningObjectTable IParseDisplayName IAsyncMoniker IBindHost IBinding IBindStatusCallback IWindowForBindingUI Compound Document Management IOleObject IOleClientSite IOleContainer IOleItemContainer IOleAdviseHolder IOleCache IOleCache2 IOleCacheControl IOleLink IRunnableObject IOleWindow IOleInPlaceObject IOleInPlaceActiveObject IOleInPlaceUIWindow IOleInPlaceFrame IOleInPlaceSite IOleCommandTarget IOleDocument IOleDocumentSite IOleDocumentView IPrint Structured Storage IPersist IPersistStorage IPersistFile IPersistStream IStorage IStream ILockBytes IPersistMoniker IPersistPropertyBag IPropertyBag 13 .

Connection Points Client (consumer) EnumConnectionPoints FindConnectionPoint Data Object (source) IConnectionPointContainer GetConnectionInterface GetConnectionPointContainer Advise Unadvise EnumConnections returns IID sends sink pointer breaks connection IConnectionPoint Connection Point sink Outgoing Interface IConnectionPoint Connection Point sink Outgoing Interface 14 .

..w hat region this is */ /* call type . integers >---HRESULT GetIDsOfNames( REFIID riid.. LCID lcid..w hat region this is */ /* pointer to requested type info object */ method ID 1st param ID 2nd param ID ...... OLECHAR** rgszNames... pVarResult.. w Reserved3... LCID lcid...w hat method to call */ /* alw ays IID_NULL */ /* locale identifier .IDispatch interface IDispatch //----< get number of type info interfaces this object supports ... union { unsigned char bVal... e...0 or 1 */ Operations: lots of member functions..... } 15 .interface IUnknown Operations: QueryInterface AddRef Release Automation Interface . used to get type info for an interface >---HRESULT GetTypeInfo( unsigned int iTInfo. similar in character to those of IDispatch //----< retrieve type information for this object...g. w flags. lcid. pExcepInfo.w hat region this is */ /* caller allocated array w ith IDs for one method */ struct DISSPARAMS Attribute: VARIANTARG* DISPID* unsigned int unsigned int rgvarg rgdispidNamedArgs cArgs cNamedArgs /* array of arguments */ /* disp Ids of named args */ /* number of args */ /* number of named args */ //----< call method or access property on this object >---HRESULT Invoke( DISPID REFIID LCID WORD DISPPARMS* VARIANT* EXCEPINFO* UINT* ) dispIdMember..either 0 or 1 >---HRESULT GetTypeInfoCount( unsigned int* pctinfo ) interface ITypeInfo /* number of type info interfaces . /* type held by union */ unsigned short w Reserved1.. DISPID* rgDispId /* alw ays IID_NULL */ /* array of names to get Ids for */ /* size of name array */ /* locale identifier . puArgError /* method index . //----< map single method name and its argument names to DISPIDs. riid... pDispParams.. /* VT_UI1 */ many more encapsulated types . unsigned int cNames. w Reserved2....method or property */ /* structure holding invoke parameters */ /* returned result packed in a variant */ /* structure holding error information */ /* index of first argument w ith error */ struct VARIANT Attribute: VARTYPE VT.. ITypeInfo** ppTInfo ) /* type information to return */ /* locale identifier .

Container supports one client site object for each embedded control. used by container before the control is activated. The control stores any persistent data in container’s document. The container supports in-place activation of control.Embedding Control in Container      Controls usually participate in building container’s user interface. 16 . The control uses a data cache object to store a static image of itself.

Loading Container  When container is loaded it loads a data cache object handler to render a static image of the control – container uses control’s IPersistStorage interface to supply a pointer to the container’s storage containing control’s cached view – data cache object loads the view – container uses the control’s IViewObject2 interface to get the data cache object to draw cached view at a container specified location   The container renders the rest of its view on its main frame window If no user action (mouse click for example) activates the control it is never loaded 17 .

OLEIVERB_OPEN. OLEIVERB_SHOW. OLEIVERB_INPLACEACTIVATE. OLEIVERB_DISCARDUNDOSTATE – container’s IOleObject calls CoCreateInstance for the control using its CLSID saved in the container’s persistent storage – container’s IOleObject uses the control’s IPersistStorage to give it a pointer to the container’s storage – The control loads its persistant data from storage – The container’s IOleObject now calls control’s IOleObject::DoVerb which creates control’s window and starts processing messages 18 . OLEIVERB_UIACTIVATE. OLEIVERB_HIDE.Activating the Control  When a user action activates the control: – container invokes IOleObject::DoVerb on its IOleObject representation of the control • OLEIVERB_PRIMARY.

When user interacts with control to change its state: – the control is an in-proc component.Modifying Container and Control State   Container’s IOleObject invokes control’s IDataObject::DAdvise passing a pointer to container’s IAdviseSink interface so control can update container. in the process of the container. and so may up-date its own window – the control uses IAdviseSink::OnDataChange to update container as needed by the application  The container communicates with the control through its IDispatch interface. 19 .

through events. 20 . and other interested components as well. – A control can define a set of events – its container would then be expected to provide a way to react to each received event – events are methods that a control invokes on its container – to make this work the control must acquire a pointer to an interface supported by the container with methods that match the events the control wants to send  We say that the control supports a source interface for events and the container must provide a sink for that interface.ActiveX Control Events  A control can also communicate with its container.

accessed via IDispatch. – the control must provide a type library describing both its incoming (method) and outgoing (event) interfaces.Establishing Events Connections  Both a control’s events and its methods are defined in dispinterfaces. – a container can read the type library to learn what methods and events it supports – the events are simply methods the control knows how to invoke – the container must dynamically create an IDispatch::invoke that supports those methods – it can do that because the methods and parameters are described by dispIDs in the the controls type library 21 .

Acquiring a Connection  The container calls control’s IProvideClassInfo2::GetClassInfo: – it acquires a pointer to an ITypeInfo object describing the control’s coclass that lists all the interfaces the control supports – container can then call ::CreateStdDispatch passing in ITypeInfo pointer which returns with a pointer to the new dispatch interface     Container then calls IConnectionPointContainer:: FindConnectionPoint passing in the IID of the control’s event interface. Now the control can notify the container about its events. The container invokes IConnectionPoint::Advise passing to the control the pointer to its newly created dispatch interface. The control returns a pointer to its IConnectionPoint interface for this source interface. 22 .

one for each property page object supported by the control. When a user askes to see a control’s properties its container calls the control’s ISpecifyPropertyPages::GetPages. For each property page the frame provides a site object supporting the IPropertyPageSite interface. Some controls provide an ISpecifyPropertyPages interface. Each property page object presents its page to the frame which builds a tabbed dialog box. 23 .Properties     A control implements a dispinterface providing access to its properties. This returns with a list of GUIDs. The container then creates a property frame which instantiates each property page using CoCreateInstance.

24 .

25 .

thus implemented by all objects. IMalloc The interface implemented by allocator objects to support memory allocation with specified ownership rules. Also support locking of an object server in memory. IEnum<X> Supports iteration (enumeration) through a sequence of structures or objects of type <X>. OLE implements a default allocator. IClassFactory[2] The interface associated with a "class object" that manufactures (instantiates) objects of that class. 26 . IClassFactory2 is defined in OLE Controls but is simply an extension to COM.Basic COM Interfaces IUnknown The base interface for all other interfaces. IClassFactory2 is an extension of IClassFactory that provides functions for handling licensing issue for object creation. Allows clients to obtain interface pointers to other interfaces supported by an object and manage objects through reference counting.

Implemented by container applications to provide container context information to compound document objects. . such as execution of verbs (action). 27 . IEnumOLEVERB Provided through IOleObject to enumerate supported verbs of an object. IOleAdviseHolder IOleClientSite Manages IAdviseSink interfaces given to compound document objects for notification.Embedding and Caching Interfaces IOleObject Primary interface through which compound document objects provide services to containers.

IOleCache2 provides containers a way to force an update of the cached presentations.More Embedding and Caching IOleCache[2] Implemented in object handlers (such as OLE's default handler) to allow containers to manage cached presentations of a compound document object. IOleCacheControl Implemented in object handlers to support the connection of the cache to another object's IDataObject implementation IRunnableObject Provides a way for objects to know when they transition from a "loaded" state to a "running" state and when they become contained in compound documents. 28 .

IViewObject[2] Implemented by an object to support direct renderings to device contexts. 29 . such as the screen or printer. IEnumFORMATETC Provided through IDataObject implementations to enumerate arrays of FORMATETC data structures. describing the data formats available from the object. as well as supporting a notification connection for view changes through IAdviseSink. IViewObject2 is an extension to IViewObject that includes an additional member for obtaining object extents. IAdviseSink2 is the same with one added method for compound document linking. and to establish or terminate a notification loop with an advise sink (IAdviseSink[2]). IDataAdviseHolder IAdviseSink[2] Helps implementers of IDataObject to manage multiple IAdviseSink connections. Receives asynchronous data change and other notifications (such as view and document changes. enumerate and query formats. IEnumSTATDATA Enumerates a set of notification connections to an IDataObject implementer.Uniform Data Transfer Interfaces IDataObject The single interface through which data transfers happen with methods to get/set data.

IConnectionPoint Provides functions to establish and terminate a generic notification connection to an object.Connection Point Interfaces IConnectionPointContainer Implemented by an object to provide access to its various connection points (IConnectionPoint implementations) for generic notification connections to the object. This handles an objects "outgoing" interfaces on the order of how IUnknown handles incoming interfaces. 30 .

. IOleInPlaceFrame Derived from IOleInPlaceUIWindow. IOleInPlaceActivateObject Supports communication between an in-place object and the container's frame and document windows. it contains a function to retrieve the window associated with the interface and for entering or exiting context-sensitive help mode. 31 .In-Place Activation Interfaces IOleWindow The base interface for other in-place activation interfaces. IOleInPlaceUIWindow Implemented on container document and frame related objects to support border space negotiation for in-place objects. this interface is implemented on a container's frame object to support not only border space negotiation but also menu merging and keyboard accelerator translation. IOleInPlaceObject Implemented on compound document objects to indicate in-place activation support. IOleInPlaceSite Implemented next to IOleClientSite in a container to indicate in-place activation support and to provide objects a way to notify the container when in-place state changes occur. it supplies activation functions to containers.

32 . such as transformation of coordinates and accelerator translation.Newer OLE Controls Interfaces IOleControl Implemented by an OLE Control to provide for keyboard mnemonic translation and notification of changes in a container's ambient properties. IOleControlSite Implemented by an OLE Control container to supply container operations to OLE Controls.

IRootStorage Implemented on the root storage object of a compound file. or block of memory. 33 . etc. and applications can provide their own to build a compound file in other storage systems. that is. ILockBytes makes any binary storage medium such as a disk file. IStream Implemented on "stream" objects to provide file I/O type functions through which components can write binary data. This interface is used to change the underlying disk file in lowmemory save operations. appear as a contiguous byte array to objects that implement IStorage and IStream. database record. the one connected to the underlying disk file. OLE provides standard disk file and memory implementations of this interface. IEnumSTATSG Enumerates STATSG structures which provide information about storage and stream objects such as open mode.Structured Storage Interfaces IStorage Implemented on "storage" objects to provide directory-like functions for the management of a storage hierarchy. element name. creation date and time. ILockBytes In OLE's Compound Files implementation.

More Structured Storage Interfaces IPersist Base interface for persistent object interfaces through which a caller can obtain the class identifier of an object that can handle the contents of the storage element. IPersistStreamInit is an interface defined in OLE Controls that extends IPersistStream with an initialization function. Compound document objects always implement this interface. IPersistFile Implemented by an object to indicate its capability of reading and writing its persistent state to an from a standard file. IPersistStorage Implemented by an object to indicate its capability of reading and writing its persistent state to an from an IStorage object. 34 . IPersistStream[Init] Implemented by an object to indicate its capability of reading and writing its persistent state to an from an IStream object.

ITypeComp Provides a way to access information needed by compilers to bind to and instantiate structures and interfaces. ICreateTypeInfo Used by tools for creating type information for individual objects. ITypeLib Used by Automation controllers to navigate information in type libraries. IProvideClassInfo Implemented by an object to provide easy access to the ITypeInfo interface that describes all the automation interfaces of that object. This interface is defined as part of OLE Controls. but is an extension of OLE Automation. 35 .OLE Automation Interfaces IDispatch Implemented by OLE Automation objects to expose their methods and properties for access by Automation controllers. ITypeInfo Used by Automation controllers to obtain type descriptions of individual objects or IDispatch interfaces.

36 . A client connects this interface to an object via connection points. IPerPropertyBrowsing Implemented by a property page object to support browsing of individual properties. IPropertyPage[2] Implemented by a property page object to support creation of UI in which a user can manipulate properties.Property Notification and Property Page Interfaces IPropNotifySink Implemented by the client of an automation object to be notified when an object's property changes as well as to control potential property changes. IPropertyPage2 is a simple extension to IPropertyPage to support browsing of properties. ISpecifyPropertyPages Implemented by an object to indicate what implementations of IPropertyPage are available for this object's properties.

IStdMarshalInfo Retrieves the class identifier of the proxy and stub implementations used to handle marshaling of a custom interface.Remoting Interfaces IExternalConnection Provides a way for objects to know when remote connections to the object are being established and terminated. 37 . the process called marshaling. IMarshal Used to package and send interface method arguments between applications (or networks).

Used to avoid relaunching applications or reloading files redundantly thereby optimizing moniker binding. This can help monikers break out of circular reference loops. 38 . IRunningObjectTable Implemented on OLE’s “running object table”. IEnumMoniker Enumerates through monikers. Used to describe track a monikers binding process to pass information between components used in the binding.Naming Interfaces IMoniker Implemented on moniker objects to provide binding and other name-related services. IParseDisplayName IBindCtx Includes functions to convert a human readable name into a moniker. which tracks which objects are currently running according to their monikers.

. IOleItemContainer Implemented by applications that support complex linking to portions of documents or to embedded objects within a document. Specifically used by the binding process of items monikers. IOleContainer Implemented by container applications to allow enumeration of the object in the container. This interface is always implemented in OLE's default handler for any object.Linking Interfaces IOleLink Provides functions for manipulating a linked object. 39 . supported alongside IOleObject.

moves in a window.Drag and Drop Interfaces IDropSource Implemented by the source of a drag-and-drop operation to control the duration of the operation and the mouse cursor. or when a drop happens. 40 . IDropTarget Implemented by registered targets for drag-and-drop operations to know when the mouse enters or leaves a window.

...) 41 ...) OnDestroy(.ATL ActiveX Control Architecture IConnectionPointImpl<...> CProxy_IAtltimCtrEvents<CAtltimCtr> CAtltimCtr Attribute: UINT m_TimerId long m_TimeToGo OLE_COLOR m_clrBackColor OLE_COLOR m_clrForeColor Operation: SetAlarm(long delay) OnDraw (ATL_DRAWINFO &) OnCreate(.> IOleControlImpl<CAtltimCtr> CComObjectRootEx IPropertyNotifySink<CAtltimCtr> CComCoClass<..) OnTimer(...

IDataObject. Defines dispatch interface members using a dispatch map.. and messages responded to using a message map. IOleControl.. . IPersist. COlePropertyPage CColorPropPage 42 ..MFC ActiveX Control Architecture CObject Implements interfaces: IUnknown. The control also defines property pages using PROPPAGEIDS macro. This creates an array of GUIDs (each property page is a COM object) which the control uses as a COM client. supports message and event routing CCmdTarget Implements class factory and provides self registration functions. IViewObject2.. ISpecifyPropertyPages. CMfctimCtrlFactory (nested Class) CRunTimeClass CMfctimCtl Added to class with DECLARE_OLECREATE_EX macro.. defines events generated using an event map. CWnd COleObjectFactory COleControl Added to class with DECLARE_DYNCREATE macro. Implements interfaces: IOleObject. IOleInPlaceActiveObject. IDispatch. Class factories are put on a linked list held by AFX_MODULE_STATE. IProvideClassInfo.. IConnectionPointContainer. IOleInPlaceObject.

IOleControlSite.MFC ActiveX Container Architecture CObject Implements IUnknown. IPropertyNotifySink Provides window behavior for control and dialog COleControlSite CWnd Provides interface for managing controls Proxy wrapper class that knows how to communicate withthe control and container's site object CMfctim CDialog CClientDlg DECLARE_ EVENTSINK_MAP DECLARE_MESSAGE_MAP Defines dispatch functions to program control and handlers for control events 43 . IDispatch (events). IOleInPlaceSite. IDispatch (ambient properties). IDispatch. and supports message and event routing CCmdTarget Implements: IOleClientSite.

) CMfctim (w rapper) Operation: SetAlarm(long) GetBackColor( ) SetBackColor( ) GetForeColor( ) SetForeColor( ) GetClsid( ) Create(...) OnDestroy( ) OnTimer(....) CClientDlg Attribute: CMfctim m_alarm Operation: OnalarmMfctimctrl1(long) OnSetDelay( ) CClientApp Operation: InitInstance( ) IDispatch SetAlarm( ) CMfctimApp Operation: DllRegisterServer( ) DllUnregisterServer( ) AfxEnableControlContainer( ) Shaded Classes are w here the developer puts control and container functionality 44 .MFC ActiveX Control and MFC Container Interaction Connection Point Protocol used to establish COleControlSite object as an event sink CCmdTarget CWinThread CWnd COleControlSite CWnd CWinThread IDispatch (events) CWinApp COleControl CDialog CWinApp CMfctimCtl COleControlModule Attribute: UINT m_Timer long m_TimeToGo dispidSetAlarm eventidAlarm Operation: SetAlarm(long) OnDraw ( ) OnCreate(..