Building a tabbed web browser

I want to recreate a simple tabbed browser. A new tab should be created every time the user clicks the "button_addTab" button or when the selected website tries to open a new window.

Here is my code:

Add a new tab by clicking a special button:

private void button_addTab_Click(object sender, EventArgs e)
{
    TabPage addedTabPage = new TabPage("tab title"); //create the new tab
    tabControl_webBrowsers.TabPages.Add(addedTabPage); //add the tab to the TabControl

    WebBrowser addedWebBrowser = new WebBrowser()
    {
        Parent = addedTabPage, //add the new webBrowser to the new tab
        Dock = DockStyle.Fill
    }
    addedWebBrowser.Navigate("www.google.com");

      

Prevent new windows from opening the site (if you know every web browser name) :

private void specificWebBrowser_NewWindow(object sender, CancelEventArgs e)
{
    WebBrowser thisWebBrowser = (WebBrowser)sender;
    e.Cancel = true;    
    TabPage addedTabPage = new TabPage("tab title");
    tabControl_webBrowsers.TabPages.Add(addedTabPage);
    WebBrowser addedWebBrowser = new WebBrowser()
    {
         Parent = addedTabPage,
         Dock = DockStyle.Fill
    } 
    addedWebBrowser.Navigate(thisWebBrowser.StatusText.ToString());
 }

      

Now my question is: How can I change the second branch of code to fit all web browsers created without names on the first call to the first code?

+3


source to share


1 answer


Try changing the first function to attach an event handler to the newly created browser:



private void button_addTab_Click(object sender, EventArgs e)
        {
            TabPage addedTabPage = new TabPage("tab title"); //create the new tab
            tabControl_webBrowsers.TabPages.Add(addedTabPage); //add the tab to the TabControl

            WebBrowser addedWebBrowser = new WebBrowser()
            {
                Parent = addedTabPage, //add the new webBrowser to the new tab
                Dock = DockStyle.Fill
            };
            addedWebBrowser.NewWindow += specificWebBrowser_NewWindow;
            addedWebBrowser.Navigate("www.google.com");
        }

      

+4


source







All Articles