How Behaviors Work
Under the Hood

In the world of Internet Explorer 5.0, "behavior" is a blanket term that wraps together a bunch of COM interfaces. The advent of HTC doesn't change the essence of behaviors, which are just COM objects written in a mix of XML and script languages.

    An HTC is simply a thin wrapper designed to hide even more details. Internet Explorer 5.0 comes with a module that works as a proxy between MSHTML (the Internet Explorer core engine) and HTCs or XML scriptlets. This proxy lives in ScrObj.dll. It uses COM to set up a dialog between MSHTML on one side and other modules called interface handlers on the other side.

    Interface handlers are the objects that virtualize a number of COM interfaces to make them appear as a single and simpler functionality to a Web page (see Figure A). Thus the keyword behavior implies IElementBehavior, IElementBehaviorFactory, and IElementBehavior-Render, while the keyword Auto-mation includes IDispatchEx, and even IConnectionPoint, ICon-nec-tionPointCon-tainer, and the like.
Figure A: Interface Handlers
Figure A: Interface Handlers

    Behaviors are COM objects. As such, you can write them either with scripting languages (the preferred way for the typical Web developer) or with any language and development tool capable of creating COM servers. There are two main reasons for using binary behaviors over scripted ones. Binary behaviors aren't human-readable, so they don't jeopardize your intellectual property, and might be a good way to hide the core code from either Internet and intranet sites. In addition, binary behaviors don't need any proxy module in the middle to translate scripting code back and forth into COM calls. In short, they give you far better performance.

    When writing behaviors with C++, you must take care of all the tasks that are normally accomplished by interface handlers. The interfaces to implement are IElementBehaviorFactory, IElementBehavior, and IElement BehaviorRender.

    When the MSHTML parser finds a word in the HTML source code that refers to a behavior, it retrieves a reference to IElementBehaviorFactory immediately and instantiates the behavior. MSHTML exposes an IElementBehaviorSite interface to let the behavior ask for the element it is attached to. Furthermore, the parser module uses the behavior's IElementBehavior as an event sink and notifies DHTML events.
Figure B: Interface Interaction
Figure B: Interface Interaction

    When the time comes for the behavior to fire events, it can rely on the host's IElementBehaviorSiteOM. This interface provides the methods needed to raise events. Finally, IElementBehaviorRender works in conjunction with IElementBehaviorSiteRender to participate in the drawing process and notify MSHTML of its drawing activity. This interface is not strictly required. The overall interaction among the interfaces is shown in Figure B.