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.

Comments (2)

  1. tobor says:

    Hi Jay,

    I’m a little new to .NET so bear with me please. I’m a little confused as to what WebBrowserFrontBack is. Googling reveals nothing except this post, and I can’t find anything about it on MSDN. Is that some idiom that I’m not aware of? Thanks.

  2. Jay A. Allen says:

    Sorry, should have clarified – WebBrowserForwardBack is the name of my project, which doubles as the default namespace. Replace this with the name of the namespace in which you defined IServiceProvider.