Click here to Skip to main content
15,180,249 members
Articles / Programming Languages / XML
Posted 20 Feb 2010

Tagged as


259 bookmarked

Web Browser in C#

Rate me:
Please Sign up or sign in to vote.
4.88/5 (149 votes)
20 Feb 2010CPOL6 min read
A tabbed Web Browser in C# with favicons, History & Favorites, Links Bar, View Source, Search, and Print functionalities.




This was my first project in C#. This article describes how to implement some of the features of a Web Browser application like managing tabs, viewing the favicon of a particular website, managing Favorites websites and Links Bar, viewing the History, searching on Google or Live Search, saving settings between application runs, viewing the source and properties of a website, printing the content of page, and others. C# has a WebBrowser control that does all the work of rendering web pages.

Implementing Tab functionality

In my main form, I added a TabControl control named browserTabControl with only one TabPage which represents the "New" tab. When the user clicks the "New" tab, then a new tab is created. The addNewTab() method shows how to add a new tab in your web browser.

private void addNewTab()
    // create a new TabPage object
    TabPage tpage = new TabPage(); 
    tpage.BorderStyle = BorderStyle.Fixed3D;
    //add the newly created TabPage
    //to the tabcontrol's collection of tab pages 
        browserTabControl.TabCount - 1, tpage);
    //create a WebBrowser object
    WebBrowser browser = new WebBrowser();
    //add the browser object to the tab page 
    //you created previously
    browser.Dock = DockStyle.Fill;
    //add some event handlers to your browser object
    browser.ProgressChanged += new 
    browser.DocumentCompleted += new 
    browser.Navigating += 
      new WebBrowserNavigatingEventHandler(Form1_Navigating);
    browser.CanGoBackChanged += 
      new EventHandler(browser_CanGoBackChanged);
    browser.CanGoForwardChanged += 
      new EventHandler(browser_CanGoForwardChanged);

The example below shows how to get the current tab:

private WebBrowser getCurrentBrowser()
    return (WebBrowser)browserTabControl.SelectedTab.Controls[0];

How to get the favicon of a website

A favicon is a 16X16, 32X32, or 64X64 pixel square icon associated with a website. This icon is called favicon.ico, and can be found in in the root directory of a website. What you have to do in order to get the favicon of a particular website is to make a request to http://websitename/favicon.ico. You can get the icon from the response stream and use it in your application. For websites that don't have a favicon, I have used a default icon.

public static Image favicon(String u, string file)
    Uri url = new Uri(u);
    String iconurl = "http://" + url.Host + "/favicon.ico";

    WebRequest request = WebRequest.Create(iconurl);
        WebResponse response = request.GetResponse();

        Stream s = response.GetResponseStream();
        return Image.FromStream(s);
    catch (Exception ex)
        //return a default icon in case 
        //the web site doesn`t have a favicon
        return Image.FromFile(file);

Links Bar

For the Links Bar, I used a ToolStrip control. A link button is represented by a ToolStripButton with the favicon image, and the website name as the text displayed on the button. The links are stored in an XML file that looks like this:

  <link url="" >Google/<link>
  <link url="">CodeProject</link>
  <link url="">Youtube/Edu</link>

The addNewLink() method shows how to add a new link. First, you open the XML file containing the links, then add a new XmlElement, setting the url attribute with the address of the website and the inner text of this element with the name you want this link to appear on the links bar. Then, you add a ToolStripButton to the links bar. The ToolStripButton control has a constructor that takes four arguments: public ToolStripButton(string text, Image image, EventHandler onClick, string name).

private void addLink(String url, string name)
   //open the xml file 
    XmlDocument myXml = new XmlDocument();
   //and a new element to the xml file
    XmlElement el = myXml.CreateElement("link");
    el.SetAttribute("url", url);
    el.InnerText = name;

    if (!File.Exists(linksXml))
        XmlElement root = myXml.CreateElement("links");
    //if the links bar is visible then 
    //you have to add a ToolStripButton
    if (linkBar.Visible == true)
       //create a new ToolStripButton object with the favicon image,
       //website name the click eventhandler to 
       //navigate to the specific web site               
        ToolStripButton b =
                  new ToolStripButton(el.InnerText, getFavicon(url), 
                  items_Click, el.GetAttribute("url"));
        b.ToolTipText = el.GetAttribute("url");
        //the MouseUp event is used 
        //for showing the context menu of this button 
        b.MouseUp += new MouseEventHandler(b_MouseUp);


The ToolStripButton control doesn't have a ContextMenu so if you want to add a context menu, you need to do some tricks. Here is my idea for solving this problem. In the designer view, I added a ContextMenu control named linkContextMenu and added some items on this context menu. When the user right-clicks a link, then this context menu is shown at the position where the mouse is. Then, you retain the website address and the name of this link (button that sent this event). For retaining the last address and name, I used two variables: adress and name. So, when the user clicks a context menu item, you can use these variables.


string adress, name;

private void b_MouseUp(object sender, MouseEventArgs e)
    ToolStripButton b = (ToolStripButton)sender;
    adress = b.ToolTipText;
    name = b.Text;

    if (e.Button == MouseButtons.Right)

Each context menu item has a click event handler. Below is an example of opening the link in a new window:

private void openInNewWindowToolStripMenuItem_Click(object sender, EventArgs e)
    WBrowser new_form = new WBrowser();

History & Favorites

For storing History and Favorites, I used two XML files:


  <item url="" 
    lastVisited="19.02.2010 12:58:03" times="6" />
  <item url="" 
    lastVisited="19.02.2010 12:52:09" times="2" />
  <item url="" 
    lastVisited="13.08.2009 20:22:52" times="1" />


   <favorit url="">
   <favorit url="">Yahoo!</favorit>

For showing History and Favorites, I used a TreeView control. Here is an example of showing history based on the site name:

private void showHistory()
    //open the xml file
    XmlDocument myXml = new XmlDocument();

    if (File.Exists(historyXml))
        DateTime now=DateTime.Now;
        if (comboBox1.Text.Equals("View By Site"))
          historyTreeView.ShowRootLines = true;
          foreach(XmlElement el in myXml.DocumentElement.ChildNodes)
              Uri site=new Uri(el.GetAttribute("url"));

              //create a new tree node
              TreeNode node =new TreeNode(el.GetAttribute("url"), 3, 3);
              //set some properties of the new tree node you created    
              node.ToolTipText = el.GetAttribute("url") + 
                               "\nLast Visited: " + 
                               el.GetAttribute("lastVisited") + 
                               "\nTimes Visited: " + 
              node.Name = el.GetAttribute("url");
              //add a context menu to this node
              node.ContextMenuStrip = histContextMenu;
              //add this node to the treeview control    

For adding a website to Favorites, I created a form named AddFovorites which will be treated as a dialog. The constructor of this class takes a string argument representing the current web address. When the user clicks the "Add to favorites" button, the AddFavorites dialog will appear. The user can choose whether to add a favorite or a link.


private void toolStripButton8_Click(object sender, EventArgs e)
    if (getCurrentBrowser().Url != null)
    {        //show the AddFavorites dialog
        AddFavorites dlg = 
           new AddFavorites(getCurrentBrowser().Url.ToString());
        DialogResult res = dlg.ShowDialog();
            //if the user clicks OK   
        if (res == DialogResult.OK)
            if (dlg.favFile == "Favorites")
                //add a favorite to xml file and in treeview
            //add a link in xml file and in links bar
            //the addLink() method is listed
            //in the Links Bar section of this article
            else addLink(getCurrentBrowser().Url.ToString(), 

The addFavorit() method is listed below. It is similar to the addLink method, except it opens another XML file containing the favorite website, and it adds a TreeNode in favTreeView.

private void addFavorit(String url, string name)
    XmlDocument myXml = new XmlDocument();
    XmlElement el = myXml.CreateElement("favorit");
    el.SetAttribute("url", url);
    el.InnerText = name;
    if (!File.Exists(favXml))
        XmlElement root = myXml.CreateElement("favorites");
    if (favoritesPanel.Visible == true)
        TreeNode node = new TreeNode(el.InnerText, 
        node.ToolTipText = el.GetAttribute("url");
        node.Name = el.GetAttribute("url");
        node.ContextMenuStrip = favContextMenu;

View Source

The WebBrowser control has a DocumentText property that represents the HTML contents of the page displayed in the control. For viewing the source of a website in Notepad, first create a temporary file, write the HTML content to this file, and then open the temporary file with Notepad.

private void sourceToolStripMenuItem_Click(object sender, EventArgs e)
    String source=("source.txt");
    StreamWriter writer =File.CreateText(source);
    Process.Start("notepad.exe", source);


On the address bar, I have a text box where the user can enter the keywords he wants to search. This text box has a KeyDown event. When the user presses "Enter", the result will be shown in the current tab. The user can choose between Google Search or Live Search in the dropdown button near the search bar.

private void searchTextBox_KeyDown(object sender, KeyEventArgs e)
    if (e.KeyCode == Keys.Enter)
        if (googleSearch.Checked == true)
            getCurrentBrowser().Navigate("http://" + 
              "" + searchTextBox.Text);
            getCurrentBrowser().Navigate("http://search." + 

Saving Settings

Sometimes a user wants to save settings between application runs. For saving settings like home page, visibility of the menu bar or links bar, I used an XML file named "settings.xml".

  <menuBar visible="True" />
  <adrBar visible="True" />
  <linkBar visible="True" />
  <favoritesPanel visible="True" />
  <SplashScreen checked="False" />

When the main form loads, these setting are read from the XML file. When the user changes a setting, the content of the XML file is changed. These changes are saved when the form is closed.

Changing the visibility of the Links Bar

In my main form, I have a context menu named toolBarContextMenu with the items in the image below. Each item has a Click event. When the user clicks one of the items in the context menu, then the visibility of that item is changed.


private void linksBarToolStripMenuItem_Click(object sender, EventArgs e)
    linkBar.Visible = !linkBar.Visible;
    this.linksBarToolStripMenuItem.Checked = linkBar.Visible;
    //settings represents the xml file 
    //"settings.xml" opened when the form loads
    settings.DocumentElement.ChildNodes[2].Attributes[0].Value = 

Changing the home page

I created a form named InternetOptions which will be treated as a dialog. The user can change the homepage, appearance, or the number of dropdown items in the address bar.


String homePage;
InternetOption optionDialog = 
  new InternetOption(getCurrentBrowser().Url.ToString());
if (optionDialog.ShowDialog() == DialogResult.OK)
    //if the user setted a home page   
    if (!optionDialog.homepage.Text.Equals(""))
        homePage = optionDialog.homepage.Text;
        //changing the setting in the xml file 
        //settings represents the xml file
        //"settings.xml" opened when the form loads
        settings.DocumentElement.ChildNodes[5].InnerText = 

Properties, Print, Print Preview, Page Setup, Save As

Some of the WebBrowser control methods are listed here:

  • public void ShowPropertiesDialog (): Opens the Internet Explorer Properties dialog box for the current document.
  • C#
    private void propertiesToolStripMenuItem_Click(object sender, EventArgs e)
  • public void ShowPageSetupDialog (): Opens the Internet Explorer Page Setup dialog box.
  • C#
    private void pageSetupToolStripMenuItem_Click(object sender, EventArgs e)
  • public void ShowPrintDialog (): Opens the Internet Explorer Print dialog box without setting the header and footer values.
  • C#
    private void printToolStripMenuItem_Click(object sender, EventArgs e)
  • public void ShowPrintPreviewDialog (): Opens the Internet Explorer Print Preview dialog box.
  • C#
    private void printPreviewToolStripMenuItem_Click(object sender, EventArgs e)
  • public void ShowSaveAsDialog (): Opens the Internet Explorer Save Web Page dialog box, or the Save dialog box of the hosted document if it is not an HTML page.
  • C#
    private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)

Cut, Copy, Paste, Select All

The WebBrowser control has a Document property that gets an HtmlDocument representing the web page currently displayed in the control. On this HtmlDocument, you can execute specific commands like "Cut" or "Copy". The examples below show how you can do this.

private void cutToolStripMenuItem_Click(object sender, EventArgs e)
    getCurrentBrowser().Document.ExecCommand("Cut", false, null);

private void copyToolStripMenuItem_Click(object sender, EventArgs e)
    getCurrentBrowser().Document.ExecCommand("Copy", false, null);

private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
    getCurrentBrowser().Document.ExecCommand("Paste", false, null);
//select all
private void selectAllToolStripMenuItem_Click(object sender, EventArgs e)
    getCurrentBrowser().Document.ExecCommand("SelectAll", true, null);

What can be done further

There are two things that can be done further: one is to save the favicons of the favorites and links in XML files. This way, when the application loads, it doesn't have to make so many requests. Another thing that can be done is to use the App.config for saving settings.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Claudia Goga
Romania Romania
MCTS | ASP.NET Developer

Comments and Discussions

QuestionWant to replace a string in javascript method Pin
rameshberugu7-Aug-19 19:46
Memberrameshberugu7-Aug-19 19:46 
Question>:-( Pin
PlatElec1-Apr-19 7:51
MemberPlatElec1-Apr-19 7:51 
Generalthanks Pin
Hooman_Kh24-Sep-16 8:33
MemberHooman_Kh24-Sep-16 8:33 
QuestionMy vote 5 and also here some fixes for problems i saw here in the users responses Pin
chocolade11-Feb-16 11:02
Memberchocolade11-Feb-16 11:02 
QuestionWeb Browser in C# Pin
Member 1173439325-Jan-16 13:55
MemberMember 1173439325-Jan-16 13:55 
QuestionPlease help Pin
Lâm Linh24-Aug-15 23:42
MemberLâm Linh24-Aug-15 23:42 
QuestionThis is awesome!!! Pin
Troy compton17-Aug-15 5:39
MemberTroy compton17-Aug-15 5:39 
QuestionHow to create new tab Pin
Member 1184136416-Jul-15 0:23
MemberMember 1184136416-Jul-15 0:23 
General*** Published to BitBucket *** Pin
Earl_McNelly19-Jun-15 17:43
MemberEarl_McNelly19-Jun-15 17:43 
Questionhistory Pin
Member 1151748330-Mar-15 5:37
MemberMember 1151748330-Mar-15 5:37 
QuestionPerfect. Working and also just what i was looking for. My vote 5. Pin
chocolade22-Feb-15 12:32
Memberchocolade22-Feb-15 12:32 
Generalcongratulate Pin
Guillermo Lazo A31-Jan-15 18:41
MemberGuillermo Lazo A31-Jan-15 18:41 
Generalcongratulate Pin
Guillermo Lazo A31-Jan-15 18:40
MemberGuillermo Lazo A31-Jan-15 18:40 
QuestionDemo Doesn't work! Pin
Mahi Uddin4-Nov-14 4:16
MemberMahi Uddin4-Nov-14 4:16 
AnswerRe: Demo Doesn't work! Pin
SIRATAMA23-Nov-14 7:23
MemberSIRATAMA23-Nov-14 7:23 
QuestionOpening in new tab Pin
Member 111212458-Oct-14 11:21
MemberMember 111212458-Oct-14 11:21 
Generalrequest Pin
Member 1034363126-May-14 19:52
MemberMember 1034363126-May-14 19:52 
QuestionContact the Author Pin
Member 1055249421-Apr-14 0:58
MemberMember 1055249421-Apr-14 0:58 
QuestionHELP PLS Pin
Member 1067944918-Mar-14 21:42
MemberMember 1067944918-Mar-14 21:42 
Questionfantastic Pin
Pedro Schneider8-Mar-14 11:49
MemberPedro Schneider8-Mar-14 11:49 
QuestionWhat about interpreting JScript? Pin
Member 1053360619-Jan-14 2:09
MemberMember 1053360619-Jan-14 2:09 
AnswerRe: What about interpreting JScript? Pin
abhi_498-Jul-14 4:40
Memberabhi_498-Jul-14 4:40 
Questiongetting mouse.location on web side area Pin
Member 104427133-Dec-13 10:20
professionalMember 104427133-Dec-13 10:20 
AnswerRe: getting mouse.location on web side area Pin
mprk16-Mar-14 23:52
Membermprk16-Mar-14 23:52 
GeneralMy vote of 5 Pin
Member 999812823-Sep-13 4:50
MemberMember 999812823-Sep-13 4:50 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.