c# webBrowser.NewWindow2 の作り方

多分、同じようなことで悩んでいる方が多いことと思います。

webBrowserを利用するプログラムを書いていると、リンクなどをクリックし別ウインドウが開かれるような場合、IEが起動してしまい、クッキーの連携が絶たれてしまいます。

このような場合に以下のようなクラスを作成しておくことにより、IEを開かずに自身が作成したwebBrowserを開くことができます。(※ソースはすべて他からのコピーを記載しています。大変、便利なものを作られる方がいるものです。)

 

◆利用手順◆

1.C#で新規プロジェクト(Windowsフォーム)を作成する。

2.クラスの追加をする。(中身は、以下記載のソース [WebBrowserEx.cs] と入れ替える。)

3.ツールボックスに WebBrowserEx コンポーネントが追加されたことを確認する。(追加されない場合は、ソリューションリビルドする。)

4.Form1.cs をコード表示し、以下掲載のソース [Form1.cs] の内容を追記する。

 

[WebBrowserEx.cs]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Security.Permissions;

namespace WebBrowserExTest
{
    public class WebBrowserEx : WebBrowser
    {

        #region NewWindow2 イベント関連

        private AxHost.ConnectionPointCookie cookie;
        private WebBrowser2EventHelper helper;

        [DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
        [DispIdAttribute(200)]
        public object Application
        {
            get
            {
                if (this.ActiveXInstance == null)
                {
                    throw new AxHost.InvalidActiveXStateException("Application", AxHost.ActiveXInvokeKind.PropertyGet);
                }
                return (this.ActiveXInstance as IWebBrowser2).Application;
            }
        }

        [DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)]
        [DispIdAttribute(552)]
        public bool RegisterAsBrowser
        {
            get
            {
                if (this.ActiveXInstance == null)
                {
                    throw new AxHost.InvalidActiveXStateException("RegisterAsBrowser", AxHost.ActiveXInvokeKind.PropertyGet);
                }
                return (this.ActiveXInstance as IWebBrowser2).RegisterAsBrowser;
            }
            set
            {
                if (this.ActiveXInstance == null)
                {
                    throw new AxHost.InvalidActiveXStateException("RegisterAsBrowser", AxHost.ActiveXInvokeKind.PropertyGet);
                }
                (this.ActiveXInstance as IWebBrowser2).RegisterAsBrowser = value;
            }
        }

        [PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
        protected override void CreateSink()
        {
            base.CreateSink();
            helper = new WebBrowser2EventHelper(this);
            cookie = new AxHost.ConnectionPointCookie(this.ActiveXInstance, helper, typeof(DWebBrowserEvents2));
        }

        [PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
        protected override void DetachSink()
        {
            if (cookie != null)
            {
                cookie.Disconnect();
                cookie = null;
            }
            base.DetachSink();
        }

        public event WebBrowserNewWindow2EventHandler NewWindow2 = (o, e) => { };

        protected virtual void OnNewWindow2(WebBrowserNewWindow2EventArgs e)
        {
            NewWindow2(this, e);
        }

        private class WebBrowser2EventHelper : StandardOleMarshalObject, DWebBrowserEvents2
        {
            private WebBrowserEx parent;

            public WebBrowser2EventHelper(WebBrowserEx parent)
            {
                this.parent = parent;
            }

            public void NewWindow2(ref object ppDisp, ref bool cancel)
            {
                var e = new WebBrowserNewWindow2EventArgs(ppDisp);
                this.parent.OnNewWindow2(e);
                ppDisp = e.ppDisp;
                cancel = e.Cancel;
            }

        }
        #endregion
    }

    public delegate void WebBrowserNewWindow2EventHandler(object sender, WebBrowserNewWindow2EventArgs e);

    public class WebBrowserNewWindow2EventArgs : CancelEventArgs
    {
        public object ppDisp { get; set; }

        public WebBrowserNewWindow2EventArgs(object ppDisp)
        {
            this.ppDisp = ppDisp;
        }
    }

    [ComImport, Guid("34A715A0-6587-11D0-924A-0020AFC7AC4D")]
    [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
    [TypeLibType(TypeLibTypeFlags.FHidden)]
    public interface DWebBrowserEvents2
    {
        [DispId(251)]
        void NewWindow2(
        [InAttribute(), OutAttribute(), MarshalAs(UnmanagedType.IDispatch)] ref object ppDisp,
        [InAttribute(), OutAttribute()] ref bool cancel);
    }

    [ComImport, Guid("D30C1661-CDAF-11D0-8A3E-00C04FC9E26E")]
    [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
    public interface IWebBrowser2
    {
        object Application { get; }
        bool RegisterAsBrowser { get; set; }
    }
}

 

[Form1.cs]

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WebBrowserExTest;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        TabControl TabControl1 = new TabControl();
        WebBrowserEx WebBrowser1;
        TabPage TabPage1;

        public Form1()
        {
            InitializeComponent();
        }

        private void webBrowserEx1_NewWindow2(object sender, ReinsKensaku2011.WebBrowserNewWindow2EventArgs e)
        {
            //WebBrowser1
            this.WebBrowser1 = new WebBrowserEx();
            this.WebBrowser1.Dock = DockStyle.Fill;
            WebBrowser1.NewWindow2 += webBrowserEx1_NewWindow2;
            //TabPage1
            this.TabPage1 = new TabPage();
            this.TabPage1.Controls.Add(WebBrowser1);
            //TabControl
            this.TabControl1.Controls.Add(TabPage1);
            this.TabControl1.SelectedTab = TabPage1;
            //新しいウィンドウが開くのを抑制
            e.ppDisp = this.WebBrowser1.Application;
            this.WebBrowser1.RegisterAsBrowser = true;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //WebBrowser1
            this.WebBrowser1 = new WebBrowserEx();
            this.WebBrowser1.Dock = DockStyle.Fill;
            WebBrowser1.NewWindow2 += webBrowserEx1_NewWindow2;
            //TabPage1
            this.TabPage1 = new TabPage();
            this.TabPage1.Controls.Add(WebBrowser1);
            //TabControl
            this.TabControl1.Dock = DockStyle.Fill;
            this.TabControl1.TabPages.Add(TabPage1);
            //Form1
            this.Text = "WebBrowserNewWindow2Event";
            this.Controls.Add(this.TabControl1);
            //
            this.WebBrowser1.GoHome();

        }

    }

}