How to get IOleSite interface of the WebBrowser in an ActiveX control
Last Update:2018-12-05
Source: Internet
Author: User
// Based on q172763 HOWTO: retrieve the top-level iwebbrowser2 interface from an ActiveX Control
Using system;
Using system. componentmodel;
Using system. Windows. forms;
Using system. drawing;
Using system. reflection;
Using system. Security;
Using system. runtime. interopservices;
Using shdocvw;
// Use strongname to apply the customized pemission set
[Assembly: assemblykeyfile (@ "C: \ key. SNK")]
// Q814669 PRB: Strong named user controls do not render in Internet Explorer
[Assembly: system. Security. allowpartiallytrustedcallers]
Namespace Microsoft. Samples. WinForms. Cs. SimpleControl
{
Public class SimpleControl: System. Windows. Forms. Control
{
Public SimpleControl (): base ()
{
Button btn = new Button ();
Btn. Parent = this;
Btn. Text = "Button1 ";
Btn. Location = new Point (10, 10 );
Btn. Click + = new EventHandler (Btn_OnClick );
Controls. Add (btn );
}
// From shlguid. h
Guid SID_STopLevelBrowser = new Guid (0x4C96BE40, 0x915C, 0x11CF, 0x99, 0xD3, 0x00, 0xAA, 0x00, 0x4A, 0xE8, 0x37 );
Guid SID_SWebBrowserApp = typeof (SHDocVw. IWebBrowserApp). GUID;
Private void Btn_OnClick (object sender, EventArgs e)
{
Try
{
Guid guidIServiceProvider = typeof (IServiceProvider). GUID;
Guid guidIWebBrowser2 = typeof (SHDocVw. IWebBrowser2). GUID;
Object objIServiceProvider2;
Object objiwebbrowser2;
Type typeioleobject = This. GetType (). getinterface ("ioleobject", true );
// Call the method on that interface
Object oleclientsite = typeioleobject. invokemember ("getclientsite ",
Bindingflags. instance | bindingflags. invokemethod | bindingflags. Public,
Null, this, null );
Iserviceprovider serviceprovider = oleclientsite as iserviceprovider;
Serviceprovider. queryservice (ref sid_stoplevelbrowser, ref guidiserviceprovider, out objiserviceprovider2 );
ServiceProvider = objIServiceProvider2 as IServiceProvider;
ServiceProvider. QueryService (ref SID_SWebBrowserApp, ref guidIWebBrowser2, out objIWebBrowser2 );
IWebBrowser2 webBrowser = objIWebBrowser2 as IWebBrowser2;
MessageBox. Show (webBrowser. LocationURL );
}
Catch (Exception ex)
{
System. Diagnostics. Debug. WriteLine (ex. ToString ());
}
}
}
[
ComImport, Guid ("6d5140c1-7436-11ce-8034-00aa006009fa "),
InterfaceType (ComInterfaceType. InterfaceIsIUnknown)
]
Public interface IServiceProvider
{
Void QueryService (ref Guid guidService, ref Guid riid, [financialas (UnmanagedType. Interface)] out object ppvObject );
}
}