【WPF】監聽WPF的WebBrowser控制項彈出新視窗的事件

來源:互聯網
上載者:User

WPF中內建一個WebBrowser控制項,當我們使用它開啟一個網頁,例如百度,然後點擊它其中的連結時,如果這個連結是會彈出一個新視窗的,那麼它會生生的彈出一個IE視窗來,而不是在內部跳到該連結。

如果使用Winform的WebBrowser控制項,我們可以監聽它的NewWindow事件,在這個事件中做一些處理,例如,在建立一個Tab來開啟,或者控制它在當前WebBrowser中跳轉。很不幸的是,WPF的WebBrowser沒有這個事件。

說到底,Winform的WB或者是WPF的WB都是在調用IE的一個控制項,因此,Winform能加上的,我們WPF一定也有辦法加上。如此,那我們就請出神器Reflector,研究一把。

首先,我們開啟Winform的WebBrowser,找到觸發NewWindow事件的代碼:

    protected virtual void OnNewWindow(CancelEventArgs e)
    {
        if (this.NewWindow != null)
        {
            this.NewWindow(this, e);
        }
    }

它是在OnNewWindow方法中觸發的。那麼,是誰調用了這個OnNewWindow呢?接著搜尋,最後在一個叫WebBrowserEvent的類裡面發現這麼一段:

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

我們接著搜NewWindow2,卻發現沒有地方顯式地調用它了。既然從方法入手沒找到,那我們就來研究一下定義這個方法的WebBrowserEvent,看看是誰在使用它。
仔細搜尋一遍,最後發現在WebBrowser的CreateSink方法中有這麼一段:

代碼

protected override void CreateSink()
{
    object activeXInstance = base.activeXInstance;
    if (activeXInstance != null)
    {
        this.webBrowserEvent = new WebBrowserEvent(this);
        this.webBrowserEvent.AllowNavigation = this.AllowNavigation;
        this.cookie = new AxHost.ConnectionPointCookie(activeXInstance, this.webBrowserEvent, typeof(UnsafeNativeMethods.DWebBrowserEvents2));
    }
}

注意這句話:

this.cookie = new AxHost.ConnectionPointCookie(activeXInstance, this.webBrowserEvent, typeof(UnsafeNativeMethods.DWebBrowserEvents2));

很顯然,這句話是關鍵。AxHost.ConnectionPointCookie類的作用是:“將一個ActiveX 控制項串連到處理該控制項的事件的用戶端”。

上面的調用中有一個很奇怪的類型:DWebBrowserEvents2,熟悉COM的童鞋應該馬上能想到,這其實是一個COM類型的定義。

 

代碼

[ComImport, TypeLibType(TypeLibTypeFlags.FHidden), InterfaceType(ComInterfaceType.InterfaceIsIDispatch), Guid("34A715A0-6587-11D0-924A-0020AFC7AC4D")]
public interface DWebBrowserEvents2
{
     ......
}

實際上,我們再去看WebBrowserEvent的定義,它恰恰是實現了這個介面的。

[ClassInterface(ClassInterfaceType.None)]
private class WebBrowserEvent : StandardOleMarshalObject, UnsafeNativeMethods.DWebBrowserEvents2
{
    ......
}

因此,上面這句話不難理解,就是定義一個實現了特定COM介面的類型,讓瀏覽器控制項的事件能夠轉寄到這個類型執行個體去處理。因此,NewWindow2其實是瀏覽器控制項去調用的。

Winform的WebBrowser我們搞清楚了,下面我們來看WPF的。其實,開啟WPF的WebBrowser代碼之後,我們會發現它跟Winform的WebBrowser機制是一樣的。一個似曾相識的CreateSink方法映入眼中:

代碼

[SecurityTreatAsSafe, SecurityCritical]
internal override void CreateSink()
{
    this._cookie = new ConnectionPointCookie(this._axIWebBrowser2, this._hostingAdaptor.CreateEventSink(), typeof(UnsafeNativeMethods.DWebBrowserEvents2));
}

這兒也有一個ConnectionPointCookie,但是它的存取權限是internal的:(
第二個參數,_hostingAdapter.CreateEventSink返回的是什麼呢:

代碼

[SecurityCritical]
internal virtual object CreateEventSink()
{
    return new WebBrowserEvent(this._webBrowser);
}

[ClassInterface(ClassInterfaceType.None)]
internal class WebBrowserEvent : InternalDispatchObject<UnsafeNativeMethods.DWebBrowserEvents2>, UnsafeNativeMethods.DWebBrowserEvents2
{
    ......
}

仍然是一個WebBrowserEvent!悲劇的是,這個WPF的WebBrowserEvent,並沒有觸發NewWindowEvent:

public void NewWindow2(ref object ppDisp, ref bool cancel)
{
}

現在知道為什麼WPF的WB控制項沒有NewWindow事件了吧?微軟的童鞋壓根兒就沒寫!

既然微軟的童鞋不寫,那我們就自己折騰一把,反正原理已經搞清楚了。

首先,我們也得定義一個DWebBrowserEvents2介面,這個我們直接通過Reflector複製一份就好了。代碼就不貼上來了。

接著,我們再仿造一個WebBrowserEvent,關鍵是要觸發NewWindow事件:

代碼

public partial class WebBrowserHelper
    {
        private class WebBrowserEvent : StandardOleMarshalObject, DWebBrowserEvents2
        {
            private WebBrowserHelper _helperInstance = null;

            public WebBrowserEvent(WebBrowserHelper helperInstance)
            {
                _helperInstance = helperInstance;
            }
            ......
            
            public void NewWindow2(ref object pDisp, ref bool cancel)
            {
                _helperInstance.OnNewWindow(ref cancel);
            }
            ......
        }
    }

 

最後,我們需要仿造Framework中的代碼,也來CreateSink一把(我承認,用了反射來取WebBrowser內部的東東,誰讓這些類型都是internal的呢):

代碼

private void Attach()
{
    var axIWebBrowser2 = _webBrowser.ReflectGetProperty("AxIWebBrowser2");
    var webBrowserEvent = new WebBrowserEvent(this);
    var cookieType = typeof(WebBrowser).Assembly.GetType("MS.Internal.Controls.ConnectionPointCookie");
    _cookie = Activator.CreateInstance(
        cookieType,
        ReflectionService.BindingFlags,
        null,
        new[] { axIWebBrowser2, webBrowserEvent, typeof(DWebBrowserEvents2) },
        CultureInfo.CurrentUICulture);
}

最後的使用:

var webBrowserHelper = new WebBrowserHelper(webBrowser);
......
webBrowserHelper.NewWindow += WebBrowserOnNewWindow;

【】

初始頁面:

點擊一個連結,預設情況下,將是彈出一個IE視窗,現在是在新的Tab中開啟:

 

【範例程式碼】

(建立按鈕點擊後,請輸入完整的網址,例如:http://www.sina.com)

/Files/RMay/WpfWebBrowser.zip

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.