【C#】WebBrowser読み込み完了後にCookieを取得しWebClientに引き渡す

WindowsForm上にWebBrowserを表示し、
読み込んだサイトのCookieをWebBrowserからWebClientに引き渡して処理を行います。

# Form1.cs
namespace WindowsFormsApplication1
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            webBrowser1.Navigate("http://test1/");
        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            // クッキーを取得する。
            string cookieStr = webBrowser1.Document.Cookie;

            // WebClientを生成する。
            WebClient wc = new WebClient();
            Encoding enc = Encoding.UTF8;

            // WebClientのヘッダ設定を行う。
            // wc.Headers.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows XP)");
            wc.Headers[HttpRequestHeader.Cookie] = cookieStr;

            // WebClientでクッキーを引き継いで他のサイトにアクセスする。
            byte[] result = wc.DownloadData("http://test2/");
            string html = enc.GetString(result);
            Console.WriteLine(html);

            // クッキーの中身を確認する。
            // string[] cookieAry = cookieStr.Split(';');
            // foreach (string str in cookieAry)
            // {
            //    MessageBox.Show(str);
            // }
        }
    }
}

【VisualStudio】オブジェクトにイベント追加

WindowsForm上にあるオブジェクトにイベントを追加します。
ボタンであればデザイナ上でボタンをダブルクリックすれば
イベント追加の設定が自動で行われますが、他のオブジェクトの場合の追加方法です。

オブジェクトをアクティブにしたら右下のプロパティの稲妻マークをクリックします。
ここに表示されているものが定義できるイベントの一覧で
白いテキストボックスをクリックするとイベント追加の設定が自動で行われます。

例として、WindowsForm上に「WebBrowser」を配置し、
WebBrowserでページ読み込み完了後を検知して処理を行いたい場合、
オブジェクトをアクティブにしたら右下のプロパティの稲妻マークをクリックし、
「DocumentCompleted」を選択すると、
イベント追加の設定が自動で行われ、「webBrowser1_DocumentCompleted」が生成されます。

# Form1.Designer.cs
namespace WindowsFormsApplication1
    partial class Form1
    {
        private void InitializeComponent()
        {
            this.webBrowser1.Location = new System.Drawing.Point(52, 193);
            this.webBrowser1.MinimumSize = new System.Drawing.Size(20, 20);
            this.webBrowser1.Name = "webBrowser1"
            this.webBrowser1.Size = new System.Drawing.Size(508, 213);
            this.webBrowser1.TabIndex = 2;
            this.webBrowser1.DocumentCompleted += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(this.webBrowser1_DocumentCompleted);
        }
    }
}
# Form1.cs
namespace WindowsFormsApplication1
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            // ここにページ読み込み完了後の処理を記載する。
        }
    }
}