Accessing the Unmanaged WebBrowser Control in Windows Forms

Lets say you're using the managed WebBrowser control in Windows Forms 2.0. At some point, you realize you want/need access to the underlying unmanaged WebBrowser control. Perhaps you need access to IWebBrower2, or you want to get the unmanaged IServiceProvider and query for something like ITravelLogStg (which exposes the URL history). How do you pull this off?

Answer: Derive a new control from WebBrowser and access the property ActiveXInstance. Here's the code to enable fetching the unmanaged IServiceProvider:

    // The unmanaged IServiceProvider, for use with our WebBrowser control.
[
ComImport,
Guid("6d5140c1-7436-11ce-8034-00aa006009fa"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)
]
public interface IServiceProvider
{
void QueryService( ref Guid guidService, ref Guid riid,
[MarshalAs(UnmanagedType.Interface)] out object ppvObject);
}

    class WebBrowser2 : WebBrowser
{
private SHDocVw.IWebBrowser2 axWebBrowser = null;

        public WebBrowser2()
{
}

        public void GetServiceProvider()
{
axWebBrowser = (SHDocVw.IWebBrowser2)this.ActiveXInstance;

            thisNamespace.IServiceProvider isp = (WebBrowserForwardBack.IServiceProvider)axWebBrowser;

            // Do what Thou Wilt...

        }
}

Note: Obtaining IWebBrowser2 depends upon importing the unmanaged COM interfaces into VS. To do this, right-click your project and select Add Reference... . Select the Browse... tab, and find shdocvw.dll in your System32 folder.