ActiveX控件中如何取得IWebBrowser2接口

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,
            [MarshalAs(UnmanagedType.Interface)] out object ppvObject);
    }
}

你可能感兴趣的:(WebBrowser)