Open link in new TAB (WebBrowser Control)

前端 未结 6 1030
遥遥无期
遥遥无期 2020-11-27 18:56

Does anybody know how to click on a link in the WebBrowser control in a WinForms application and then have that link open in a new tab inside my TabControl?

I\'ve be

6条回答
  •  -上瘾入骨i
    2020-11-27 19:22

    You simply cancel the new window event and handle the navigation and tab stuff yourself.

    Here is a fully working example. This assumes you have a tabcontrol and at least 1 tab page in place.

    using System.ComponentModel;
    using System.Windows.Forms;
    
    namespace stackoverflow2
    {
    
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
                this.webBrowser1.NewWindow += WebBrowser1_NewWindow;
                this.webBrowser1.Navigated += Wb_Navigated;
                this.webBrowser1.DocumentText=
                 ""+
                 "Title"+
                 ""+
                 " test "+
                 ""+
                 "";
            }
            private void WebBrowser1_NewWindow(object sender, CancelEventArgs e)
            {
                e.Cancel = true; //stop normal new window activity
    
                //get the url you were trying to navigate to
                var url= webBrowser1.Document.ActiveElement.GetAttribute("href");
    
                //set up the tabs
                TabPage tp = new TabPage();
                var wb = new WebBrowser();
                wb.Navigated += Wb_Navigated;
                wb.Size = this.webBrowser1.Size;
                tp.Controls.Add(wb);
                wb.Navigate(url);
                this.tabControl1.Controls.Add(tp);
                tabControl1.SelectedTab = tp;
            }
    
            private void Wb_Navigated(object sender, WebBrowserNavigatedEventArgs e)
            {
                tabControl1.SelectedTab.Text = (sender as WebBrowser).DocumentTitle;
            }
        }
    }
    

提交回复
热议问题