内容摘要 -
全文 -
Build a Managed BHO and Plug into the Browser
With the amount of time we spend touring the Internet for information, enhancing the browsing experience has never been more important. Internet Explorer has an extensibility model supporting a variety of browser plug-ins. You have probably seen and used them yourself: the Google toolbar, the Babelfish Translator, or the ever-popular variety of popup blockers. Plug-ins such as these may come in the form of basic Browser Helper Objects (BHOs) or other browser extensions such as Explorer Bars and docking Tool Bands. In any case, they enrich the browsing experience in some way by integrating otherwise cumbersome or elusive functionality. They do this by implementing a required set of predefined COM interfaces and by communicating with interfaces exposed by IE's Web browser object model.
Many a BHO has been implemented using lightweight ATL components in C++, but for those who have fully embraced C# and spend the majority of time writing managed code, the thought of revisiting COM and ATL probably seems a lousy idea. Fortunately, the COM interoperability support provided by the .NET Framework gives us a way to build 100 percent managed components and to control how they are exposed to COM. In this article I will show you how to create a managed BHO that responds to browser events and discuss the interoperability features that make it possible.
download source code
Here We Are...Talking COM Again
Prior to .NET I fancied myself a pretty good COM developer, with years of experience developing components with C++, ATL, MFC and VB. For that reason, COM interoperability was a subject near and dear to me in the early days of .NET. But, as time passed, more and more of my .NET development became pure, and COM became a distant memory. But, every once in a great while, for example, while I was porting a legacy ATL BHO to C#, I find myself summoning from past COM experiences.
In the case of the BHO, I had to gather interface identifiers to import existing COM interfaces and review the rules of reference counting ...yet again. The simplest form of BHO is a component that, once registered, is loaded by IE and can both communicate with IE's object model and hook into its useful browsing events. A BHO does not need to expose a visible user interface to be effective. IE loads any registered BHOs and provides them with reference to its container site (the Web browser class in this case), and from there BHOs decide what events to subscribe to and what parts of the IE object model to communicate with.
This requires two-way communication between managed and unmanaged code. In the sample application the managed component, Observer.dll, is registered so COM clients can consume it, and the .NET runtime dynamically generates a COM Callable Wrapper (CCW) that exposes COM interfaces to those clients. When you set the project properties option to register the assembly for COM interoperability, the
|