Sunteți pe pagina 1din 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

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

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.

ActiveX Properties

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

Automation - IDispatch Interface

Allows scripting languages, which dont know anything about interface pointers, 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 - DISPPARAMS structure - DISPID

IDispatch Query Interf ace AddRef Release GetTy peInf oCount GetTy peInf o GetIDsOf Names Inv oke

ActiveX Control Functionality

A control is:

A control usually has:


A COM object: A User Interface: Createable

Properties, 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, arrow keys, help

ActiveX Control in Container

container invokes control's methods

Control Container

control sends event notification

ActiveX Control

properties are examined and modified

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

Invoking a Controls 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

interface IUnknown
Operations: QueryInterface AddRef Release

Automation Interface - IDispatch

interface IDispatch
//----< get number of type info interfaces this object supports - either 0 or 1 >---HRESULT GetTypeInfoCount( unsigned int* pctinfo )

interface ITypeInfo
/* number of type info interfaces - 0 or 1 */ Operations: lots of member functions, similar in character to those of IDispatch

//----< retrieve type information for this object, used to get type info for an interface >---HRESULT GetTypeInfo( unsigned int iTInfo, LCID lcid, ITypeInfo** ppTInfo ) /* type information to return */ /* locale identifier - w hat region this is */ /* pointer to requested type info object */ method ID 1st param ID 2nd param ID ....

//----< map single method name and its argument names to DISPIDs, e.g., integers >---HRESULT GetIDsOfNames( REFIID riid, OLECHAR** rgszNames, unsigned int cNames, LCID lcid, DISPID* rgDispId

/* alw ays IID_NULL */ /* array of names to get Ids for */ /* size of name array */ /* locale identifier - 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, riid, lcid, w flags, pDispParams, pVarResult, pExcepInfo, puArgError /* method index - w hat method to call */ /* alw ays IID_NULL */ /* locale identifier - w hat region this is */ /* call type - 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; /* type held by union */ unsigned short w Reserved1, w Reserved2, w Reserved3; union { unsigned char bVal; /* VT_UI1 */ many more encapsulated types .................................. }

15

Embedding Control in Container


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

16

Loading Container

When container is loaded it loads a data cache object handler to render a static image of the control
container uses controls IPersistStorage interface to supply a pointer to the containers storage containing controls cached view data cache object loads the view container uses the controls 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

Activating the Control

When a user action activates the control:


container invokes IOleObject::DoVerb on its IOleObject representation of the control
OLEIVERB_PRIMARY, OLEIVERB_SHOW, OLEIVERB_OPEN, OLEIVERB_HIDE, OLEIVERB_UIACTIVATE, OLEIVERB_INPLACEACTIVATE, OLEIVERB_DISCARDUNDOSTATE

containers IOleObject calls CoCreateInstance for the control using its CLSID saved in the containers persistent storage containers IOleObject uses the controls IPersistStorage to give it a pointer to the containers storage The control loads its persistant data from storage The containers IOleObject now calls controls IOleObject::DoVerb which creates controls window and starts processing messages

18

Modifying Container and Control State

Containers IOleObject invokes controls IDataObject::DAdvise passing a pointer to containers IAdviseSink interface so control can update container. When user interacts with control to change its state:
the control is an in-proc component, 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

ActiveX Control Events

A control can also communicate with its container, and other interested components as well, through events.
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.

20

Establishing Events Connections

Both a controls events and its methods are defined in dispinterfaces, accessed via IDispatch.
the control must provide a type library describing both its incoming (method) and outgoing (event) interfaces. 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 controls IProvideClassInfo2::GetClassInfo:


it acquires a pointer to an ITypeInfo object describing the controls 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 controls event interface. The control returns a pointer to its IConnectionPoint interface for this source interface. The container invokes IConnectionPoint::Advise passing to the control the pointer to its newly created dispatch interface. Now the control can notify the container about its events.
22

Properties

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

23

24

25

Basic COM Interfaces


IUnknown

The base interface for all other interfaces, thus implemented by all objects. Allows clients to obtain interface pointers to other interfaces supported by an object and manage objects through reference counting.

IMalloc

The interface implemented by allocator objects to support memory allocation with specified ownership rules. OLE implements a default allocator.

IClassFactory[2]

The interface associated with a "class object" that manufactures (instantiates) objects of that class. Also support locking of an object server in memory. IClassFactory2 is an extension of IClassFactory that provides functions for handling licensing issue for object creation. IClassFactory2 is defined in OLE Controls but is simply an extension to COM.

IEnum<X>

Supports iteration (enumeration) through a sequence of structures or objects of type <X>.

26

Embedding and Caching Interfaces


IOleObject

Primary interface through which compound document objects provide services to containers, such as execution of verbs (action).

IEnumOLEVERB

Provided through IOleObject to enumerate supported verbs of an object.

IOleAdviseHolder IOleClientSite

Manages IAdviseSink interfaces given to compound document objects for notification. Implemented by container applications to provide container context information to compound document objects. .

27

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. IOleCache2 provides containers a way to force an update of the cached presentations.

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

Uniform Data Transfer Interfaces


IDataObject
The single interface through which data transfers happen with methods to get/set data, enumerate and query formats, 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. IAdviseSink2 is the same with one added method for compound document linking.

IViewObject[2]

Implemented by an object to support direct renderings to device contexts, such as the screen or printer, 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.

IEnumFORMATETC

Provided through IDataObject implementations to enumerate arrays of FORMATETC data structures, describing the data formats available from the object.

IEnumSTATDATA

Enumerates a set of notification connections to an IDataObject implementer.

29

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.

IConnectionPoint

Provides functions to establish and terminate a generic notification connection to an object.

30

In-Place Activation Interfaces


IOleWindow
The base interface for other in-place activation interfaces; it contains a function to retrieve the window associated with the interface and for entering or exiting context-sensitive help mode.

IOleInPlaceObject

Implemented on compound document objects to indicate in-place activation support; it supplies activation functions to containers..

IOleInPlaceActivateObject

Supports communication between an in-place object and the container's frame and document windows.

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.

IOleInPlaceUIWindow

Implemented on container document and frame related objects to support border space negotiation for in-place objects.

IOleInPlaceFrame

Derived from IOleInPlaceUIWindow, 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.

31

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, such as transformation of coordinates and accelerator translation.

32

Structured Storage Interfaces


IStorage
Implemented on "storage" objects to provide directory-like functions for the management of a storage hierarchy.

IStream

Implemented on "stream" objects to provide file I/O type functions through which components can write binary data.

IRootStorage

Implemented on the root storage object of a compound file, that is, the one connected to the underlying disk file. This interface is used to change the underlying disk file in lowmemory save operations.

ILockBytes

In OLE's Compound Files implementation, ILockBytes makes any binary storage medium such as a disk file, database record, or block of memory, appear as a contiguous byte array to objects that implement IStorage and IStream. OLE provides standard disk file and memory implementations of this interface, and applications can provide their own to build a compound file in other storage systems.

IEnumSTATSG

Enumerates STATSG structures which provide information about storage and stream objects such as open mode, element name, creation date and time, etc. 33

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.

IPersistStorage

Implemented by an object to indicate its capability of reading and writing its persistent state to an from an IStorage object. Compound document objects always implement this interface.

IPersistStream[Init]

Implemented by an object to indicate its capability of reading and writing its persistent state to an from an IStream object. IPersistStreamInit is an interface defined in OLE Controls that extends IPersistStream with an initialization function. IPersistFile Implemented by an object to indicate its capability of reading and writing its persistent state to an from a standard file.

34

OLE Automation Interfaces


IDispatch Implemented by OLE Automation objects to expose their methods and properties for access by Automation controllers. ITypeLib
Used by Automation controllers to navigate information in type libraries.

ITypeInfo Used by Automation controllers to obtain type descriptions of individual objects or IDispatch
interfaces.

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.

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

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. A client connects this interface to an object via connection points.

ISpecifyPropertyPages

Implemented by an object to indicate what implementations of IPropertyPage are available for this object's properties.

IPropertyPage[2]

Implemented by a property page object to support creation of UI in which a user can manipulate properties. IPropertyPage2 is a simple extension to IPropertyPage to support browsing of properties.

IPerPropertyBrowsing

Implemented by a property page object to support browsing of individual properties.

36

Remoting Interfaces
IExternalConnection
Provides a way for objects to know when remote connections to the object are being established and terminated.

IMarshal

Used to package and send interface method arguments between applications (or networks), the process called marshaling.

IStdMarshalInfo

Retrieves the class identifier of the proxy and stub implementations used to handle marshaling of a custom interface.

37

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. Used to describe track a monikers binding process to pass information between components used in the binding. This can help monikers break out of circular reference loops.

IEnumMoniker

Enumerates through monikers.

IRunningObjectTable

Implemented on OLEs running object table, which tracks which objects are currently running according to their monikers. Used to avoid relaunching applications or reloading files redundantly thereby optimizing moniker binding.

38

Linking Interfaces
IOleLink
Provides functions for manipulating a linked object, supported alongside IOleObject. This interface is always implemented in OLE's default handler for any object.

IOleContainer

Implemented by container applications to allow enumeration of the object in the container.

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..

39

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.

IDropTarget

Implemented by registered targets for drag-and-drop operations to know when the mouse enters or leaves a window, moves in a window, or when a drop happens.

40

ATL ActiveX Control Architecture

IConnectionPointImpl<...> IOleControlImpl<CAtltimCtr>

CComObjectRootEx

IPropertyNotifySink<CAtltimCtr>

CComCoClass<...>

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(...) OnDestroy(...) OnTimer(...)

41

MFC ActiveX Control Architecture

CObject

Implements interfaces: IUnknown, IDispatch, supports message and event routing

CCmdTarget

Implements class factory and provides self registration functions.

Implements interfaces: IOleObject, IConnectionPointContainer, IOleControl, IPersist,..., IOleInPlaceObject, IOleInPlaceActiveObject, IViewObject2, IDataObject, ISpecifyPropertyPages, IProvideClassInfo, ...

CWnd

COleObjectFactory

COleControl Added to class with DECLARE_DYNCREATE macro.

CMfctimCtrlFactory (nested Class)

CRunTimeClass

CMfctimCtl

Added to class with DECLARE_OLECREATE_EX macro. Class factories are put on a linked list held by AFX_MODULE_STATE.

Defines dispatch interface members using a dispatch map, defines events generated using an event map, and messages responded to using a message map. 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.

COlePropertyPage

CColorPropPage

42

MFC ActiveX Container Architecture

CObject Implements IUnknown, IDispatch, and supports message and event routing CCmdTarget

Implements: IOleClientSite, IOleInPlaceSite, IOleControlSite, IDispatch (events), IDispatch (ambient properties), 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

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(...) OnDestroy( ) OnTimer(...)

CMfctim (w rapper) Operation: SetAlarm(long) GetBackColor( ) SetBackColor( ) GetForeColor( ) SetForeColor( ) GetClsid( ) Create(...)

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

S-ar putea să vă placă și