SoFunction
Updated on 2025-03-06

C# implements multi-tab browser controls

This article shares the design and implementation of C# multi-tab browser controls for your reference in detail. The specific content is as follows

1. Why do we need multi-tab browser controls
The project needs to use WinForm applications to wrap the browser shell of the BS application. There is no configuration attribute for multi-tab browsing in .NET's WebBrowser. We need to implement multi-tab browser controls to achieve the purpose of wrapping the BS application without popping up the IE browser window.

2. What knowledge do we need to know
2.1. WebBrowser Control
The WebBrowser control provides a managed wrapper for the WebBrowser ActiveX control. Hosted wrappers allow you to display web pages in Windows Forms client applications. Using the WebBrowser control, you can copy the Internet Explorer Web browsing feature in your application, disable the default Internet Explorer feature, and use the control as a simple HTML document viewer.

l  How to: Use the WebBrowser control to locate the URL

this.("");

l  WebBrowser's CreateSink method and DetachSink method

The CreateSink method associates the underlying ActiveX control with clients that can handle control events.

The DetachSink method enables the event handling client attached to the CreateSink method from the underlying ActiveX control.

The following code example demonstrates how to use this method in a class derived from WebBrowser that complements the regular WebBrowser events using the NavigateError event in the OLE DWebBrowserEvents2 interface.

using System;

using ;

using ;

using ;

 

namespace WebBrowserExtensibility

{

  [PermissionSetAttribute(, Name="FullTrust")]

  public class Form1 : Form

  {

    [STAThread]

    public static void Main()

    {

      (new Form1());

    }

    private WebBrowser2 wb = new WebBrowser2();

    public Form1()

    {

       = ;

       += new

        WebBrowserNavigateErrorEventHandler(wb_NavigateError);

      (wb);

      ("");

    }

    private void wb_NavigateError(

      object sender, WebBrowserNavigateErrorEventArgs e)

    {

      // Display an error message to the user.

      ("Cannot navigate to " + );

    }

  }

 

  public class WebBrowser2 : WebBrowser

  {

     cookie;

    WebBrowser2EventHelper helper;

    [PermissionSetAttribute(, Name="FullTrust")]

    protected override void CreateSink()

    {

      ();

      helper = new WebBrowser2EventHelper(this);

      cookie = new (

        , helper, typeof(DWebBrowserEvents2));

    }

 

    [PermissionSetAttribute(, Name="FullTrust")]

    protected override void DetachSink()

    {

      if (cookie != null)

      {

        ();

        cookie = null;

      }

      ();

    }

    public event WebBrowserNavigateErrorEventHandler NavigateError;

    protected virtual void OnNavigateError(

      WebBrowserNavigateErrorEventArgs e)

    {

      if ( != null)

      {

        (this, e);

      }

    }

    private class WebBrowser2EventHelper :

      StandardOleMarshalObject, DWebBrowserEvents2

    {

      private WebBrowser2 parent;

 

      public WebBrowser2EventHelper(WebBrowser2 parent)

      {

         = parent;

      }

 

      public void NavigateError(object pDisp, ref object url,

        ref object frame, ref object statusCode, ref bool cancel)

      {

        // Raise the NavigateError event.

        (

          new WebBrowserNavigateErrorEventArgs(

          (String)url, (String)frame, (Int32)statusCode, cancel));

      }

    }

  }

  public delegate void WebBrowserNavigateErrorEventHandler(object sender,

    WebBrowserNavigateErrorEventArgs e);

  public class WebBrowserNavigateErrorEventArgs : EventArgs

  {

    private String urlValue;

    private String frameValue;

    private Int32 statusCodeValue;

    private Boolean cancelValue;

 

    public WebBrowserNavigateErrorEventArgs(

      String url, String frame, Int32 statusCode, Boolean cancel)

    {

      urlValue = url;

      frameValue = frame;

      statusCodeValue = statusCode;

      cancelValue = cancel;

    }

 

    public String Url

    {

      get { return urlValue; }

      set { urlValue = value; }

    }

 

    public String Frame

    {

      get { return frameValue; }

      set { frameValue = value; }

    }

 

    public Int32 StatusCode

    {

      get { return statusCodeValue; }

      set { statusCodeValue = value; }

    }

 

    public Boolean Cancel

    {

      get { return cancelValue; }

      set { cancelValue = value; }

    }

  }

  [ComImport, Guid("34A715A0-6587-11D0-924A-0020AFC7AC4D"),

  InterfaceType(),

  TypeLibType()]

  public interface DWebBrowserEvents2

  {

    [DispId(271)]

    void NavigateError(

      [In, MarshalAs()] object pDisp,

      [In] ref object URL, [In] ref object frame,

      [In] ref object statusCode, [In, Out] ref bool cancel);

  }

}

l  WebBrowser. DocumentCompleted Event

Occurs when the WebBrowser control completes loading the document.

Handles DocumentCompleted events and receive notifications when new documents complete loading. If the DocumentCompleted event occurs, the new document is fully loaded, meaning that the contents of the document can be accessed through the Document, DocumentText, or DocumentStream properties.

2.2. TabControl control
The TabControl control is a Windows Form multiple tab controls that resemble the labels in the partition card and the filing cabinet folder in the notebook. The tab can contain pictures and other controls. You can use this tab control to generate multi-page dialogs that can be found in many places in the Windows operating system, such as the "Show" property of the Control Panel.

l  How to:Add controls to tab page

(new Button()); 

l  How to:Add and remove tabs using Windows Forms TabControl

Add a tab

string title = "TabPage " + ( + 1).ToString();

TabPage myTabPage = new TabPage(title);

(myTabPage);

Remove the tab

(); 

l  Event

If the DrawMode property is set to OwnerDrawFixed, it raises a DrawItem event whenever a TabControl needs to draw one of its tabs. To customize the appearance of a tab, provide your own drawing code in the handler for the DrawItem event.

The following code example creates a TabControl containing a TabPage. This example declares an event handler and is used to draw strings and Rectangle on tabPage1. The event handler is bound to the DrawItem event.

using ;

using ;

public class Form1 : Form

{

  private Rectangle tabArea;

  private RectangleF tabTextArea;

  public Form1()

  {

    TabControl tabControl1 = new TabControl();

    TabPage tabPage1 = new TabPage();

     = ;

     = ;

    (tabPage1);

     = new Size(80, 30);

     = new Point(25, 25);

     = new Size(250, 250);

     = 0;

    ClientSize = new Size(300, 300);

    (tabControl1);

    tabArea = (0);

    tabTextArea = (RectangleF)(0);

     += new DrawItemEventHandler(DrawOnTab);

  }

  private void DrawOnTab(object sender, DrawItemEventArgs e)

  {

    Graphics g = ;

    Pen p = new Pen();

    Font font = new Font("Arial", 10.0f);

    SolidBrush brush = new SolidBrush();

    (p, tabArea);

    ("tabPage1", font, brush, tabTextArea);

  }

  static void Main()

  {

    (new Form1());

  }

}

3. How do we design multi-tab browser controls
Functional features that need to be implemented:

l  Implement the link or window that opens the BS application to jump to the tab instead of a new window.

l  Implement the closing and creation of tabs. Note that there is only one tab and the closing picture button cannot appear when the tab is not available.

We mainly use TabControl and WebBrowser to implement multi-tab browser control development.

Now introduce the main control implementation code.

u  The new tab page code is implemented as follows:

public void CreateNewTabPage(string url)

{

  ExtendedWebBrowser web = new ExtendedWebBrowser();

   = "WebBroswer" + _webBrowserLists.();

   = ;

   = new Padding(0, 0, 0, 0);

   += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);

   += new EventHandler(webBrowser1_BeforeNewWindow);

  (url);

  _webBrowserLists.Add(web);

 

  TabPage tbp = new TabPage();

   = "TabPage" + ();

   = "Blank Page";

   = new Padding(0, 3, 0, 0);

   = new Padding(0, 3, 0, 0);

   = 0;

  (web);

 

  this.(tbp);

  this. = tbp;

}

 

u Implement the code in the drawing tab of the web page title and picture close button as follows:

private void tabControl1_DrawItem(object sender, DrawItemEventArgs e)

{

 

  try

  {

    Graphics g = ;

 

    Rectangle tabRectangle = this.();

 

    //Add TabPage attribute first
    (this.[].Text

    , , ,  + 3,  + 3);

 

    if ( > 1)

    {

      //Draw a rectangular frame
      using (Pen p = new Pen())

      {

        ( - (CLOSE_SIZE + 3), 2);

         = CLOSE_SIZE;

         = CLOSE_SIZE;

        (p, tabRectangle);

      }

 

      ( ==  ? ["closeSelected"] : ["close"], new Point(, ));

 

    }

    ();

  }

  catch (Exception ex)

  {

    throw (ex);

  }

}

u  The code implementation is as follows when the Webbrowser control is completed and when the Webbrowser control is created in a new window:

private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)

{

  ExtendedWebBrowser web = (ExtendedWebBrowser)(sender);

  string title = ();

  TabPage tb = (TabPage);

   =  > 6 ? (0, 6) + "..." : title;

  if ( == tb)

  {

     = title;

  }

}

private void webBrowser1_BeforeNewWindow(object sender,  e)

{

  WebBrowserExtendedNavigatingEventArgs eventArgs = e as WebBrowserExtendedNavigatingEventArgs;

  CreateNewTabPage();

   = true;

}

The above is all about this article, I hope it will be helpful to everyone's learning.