WebBrowser Open link in new TAB not in IE

有朋友詢問「vb.net 自製瀏覽器開分頁 獲取原始碼問題」,

主要是在Windows Form 使用 TabControl + WebBrowser 來呈現網頁。

但是當網頁中的 link 如果 target 為 _blank  時,

User 按下Link 就會使用 IE 來開啟新的網頁。

有辦法新增一個 TabPage + WebBrowser 來開啟新的網頁嗎?

我們可以參考「Extended WebBrowser Control Series:NewWindow2 Events in the C# WebBrowserControl」這篇文章,

使用 ExtendedWebBrowser 來呈現網頁,

首先建立 C# 類別庫專案,然後將 「Extended WebBrowser Control Series:NewWindow2 Events in the C# WebBrowserControl」 的程式加入建立的類別之中,

之後在 Windows Form VB.NET 專案中,加入那個 Extended WebBrowser 專案參考,畫面先放入 TabControl (Name為TabControl1),

然後在程式中動態建立 TabPage 及 ExtendedWebBrowser ,並訂閱 NewWindow2 Event(在 InitWebBrowserEvents Method中),如下,

Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Try
            Dim tab As New TabPage
            tab.Text = "Loading..."
            Dim brws As New ExtendedWebBrowser
            brws.Dock = DockStyle.Fill
            brws.ScriptErrorsSuppressed = True
            brws.Tag = tab
            brws.Parent = tab

            InitWebBrowserEvents(brws)
            Me.TabControl1.TabPages.Add(tab)
            Me.TabControl1.SelectedTab = tab
            Dim initUrl As String = "https://dotblogs.com.tw/rainmaker/2017/02/16/232531"
            brws.Navigate(initUrl)

        Catch ex As Exception
            MsgBox(ex.ToString())
        End Try
    End Sub




    Sub InitWebBrowserEvents(wb As ExtendedWebBrowser)
        AddHandler wb.NewWindow2, AddressOf WebBrowser_NewWindow2
        AddHandler wb.Navigated, AddressOf WebBrowser_Navigated
    End Sub

    Private Sub WebBrowser_Navigated(sender As Object, e As WebBrowserNavigatedEventArgs)
        Dim tab As TabPage = TryCast(sender, WebBrowser).Parent
        If (IsNothing(tab) = False AndAlso tab.Text = "Loading...") Then
            tab.Text = e.Url.ToString()
        End If
    End Sub

    Private Sub WebBrowser_NewWindow2(sender As Object, e As NewWindow2EventArgs)
        Try
            Dim tab As New TabPage
            tab.Text = "Loading..."
            Dim brws As New ExtendedWebBrowser
            brws.Dock = DockStyle.Fill
            brws.ScriptErrorsSuppressed = True
            brws.Tag = tab
            brws.Parent = tab
            e.PPDisp = brws.Application
            InitWebBrowserEvents(brws)
            Me.TabControl1.TabPages.Add(tab)
            Me.TabControl1.SelectedTab = tab

        Catch ex As Exception

        End Try
    End Sub
End Class

完整的測試專案在 https://github.com/rainmakerho/WebBrowserNewWindowDemo

參考資料

Extended WebBrowser Control Series:NewWindow2 Events in the C# WebBrowserControl

Open link in new TAB (WebBrowser Control)

Hi, 

亂馬客Blog已移到了 「亂馬客​ : Re:從零開始的軟體開發生活

請大家繼續支持 ^_^