3

I see an example from the website http://msdn.microsoft.com/en-us/library/system.windows.controls.webbrowser%28v=VS.90%29.aspx

Here they are using a statement like:

 SHDocVw.DWebBrowserEvents_Event wbEvents = (SHDocVw.DWebBrowserEvents_Event)myWebBrowser2;
            SHDocVw.DWebBrowserEvents2_Event wbEvents2 = (SHDocVw.DWebBrowserEvents2_Event)myWebBrowser2;

When i compile the program i am getting the following error. Am i missing anything?

Cannot convert type 'System.Windows.Controls.WebBrowser' to 'SHDocVw.DWebBrowserEvents'

logeeks
  • 4,849
  • 15
  • 62
  • 93

1 Answers1

4

The exception tells you that your myWebBrowser2 is of type 'System.Windows.Controls.WebBrowser'. However in the example it is of type 'SHDocVw.IWebBrowser2'. It seems you have skipped the part where they extract the IWebBrowser2 from the WPF WebBrowser control (in this example 'myWebBrowser' is your WebBrowser control):

[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]   
[Guid("6d5140c1-7436-11ce-8034-00aa006009fa")]  
internal interface IServiceProvider   
{
   [return: MarshalAs(UnmanagedType.IUnknown)]
   object QueryService(ref Guid guidService, ref Guid riid);
}

static readonly Guid SID_SWebBrowserApp = new Guid("0002DF05-0000-0000-C000-000000000046");   
...   
IServiceProvider serviceProvider = (IServiceProvider)myWebBrowser.Document;
Guid serviceGuid = SID_SWebBrowserApp;
Guid iid = typeof(SHDocVw.IWebBrowser2).GUID;
SHDocVw.IWebBrowser2 myWebBrowser2 = (SHDocVw.IWebBrowser2) serviceProvider.QueryService(ref serviceGuid, ref iid);
...

And then myWebBrowser2 is ready for interaction.

Edwin de Koning
  • 14,209
  • 7
  • 56
  • 74