Click here to Skip to main content
11,928,352 members (51,248 online)
Click here to Skip to main content
Add your own
alternative version


227 bookmarked

Web Browser in C#

, 20 Feb 2010 CPOL
Rate this:
Please Sign up or sign in to vote.
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.
  • private void propertiesToolStripMenuItem_Click(object sender, EventArgs e)
  • public void ShowPageSetupDialog (): Opens the Internet Explorer Page Setup dialog box.
  • 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.
  • private void printToolStripMenuItem_Click(object sender, EventArgs e)
  • public void ShowPrintPreviewDialog (): Opens the Internet Explorer Print Preview dialog box.
  • 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.
  • 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

You may also be interested in...

Comments and Discussions

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
Md.Mahiuddin4-Nov-14 4:16
memberMd.Mahiuddin4-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
memberMember 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 
GeneralMy vote of 5 Pin
mihai23420-Sep-13 17:48
membermihai23420-Sep-13 17:48 
GeneralMy vote of 5 Pin
Amir Mohammad Nasrollahi10-Aug-13 22:48
professionalAmir Mohammad Nasrollahi10-Aug-13 22:48 
GeneralMy vote of 5 Pin
csharpbd25-Jun-13 14:48
membercsharpbd25-Jun-13 14:48 
QuestionHow to open in new tab if new window is created by javascript ? Pin
jrniak20-Jun-13 18:21
memberjrniak20-Jun-13 18:21 
Questionhow to get the link from the page? Pin
Syed Sirajul Islam Anik3-Jun-13 8:55
memberSyed Sirajul Islam Anik3-Jun-13 8:55 
GeneralAwesome Work ... Pin
Rohan Rai2-May-13 5:52
memberRohan Rai2-May-13 5:52 
Newsregarding working Pin
Dev_ashish30-Jan-13 19:05
memberDev_ashish30-Jan-13 19:05 
QuestionHelp Pin
hezha30-Jan-13 9:04
memberhezha30-Jan-13 9:04 
QuestionThank you Pin
hezha30-Jan-13 8:54
memberhezha30-Jan-13 8:54 
QuestionDoesnt compile Pin
Member 969519918-Dec-12 3:06
memberMember 969519918-Dec-12 3:06 
AnswerRe: Doesnt compile Pin
schnrwt5-Apr-14 16:15
memberschnrwt5-Apr-14 16:15 
Generalgood work Pin
alibensaid5-Dec-12 0:07
memberalibensaid5-Dec-12 0:07 
GeneralMy vote of 5 Pin
Member 34159510-Oct-12 16:58
memberMember 34159510-Oct-12 16:58 
Questionhelp plz Pin
Saba Ahmmad7-Oct-12 7:06
memberSaba Ahmmad7-Oct-12 7:06 
GeneralMy vote of 5 Pin
Sergio Andrés Gutiérrez Rojas26-Sep-12 10:55
memberSergio Andrés Gutiérrez Rojas26-Sep-12 10:55 
GeneralMy vote of 4 Pin
hombre3115-Sep-12 11:13
memberhombre3115-Sep-12 11:13 
Generalopen a project on visual c#2010express edition Pin
kamelsondi5-Sep-12 23:55
memberkamelsondi5-Sep-12 23:55 
GeneralMy vote of 5 Pin
nik24213-Sep-12 0:54
membernik24213-Sep-12 0:54 
Answerwerbby Pin
code cOmRAdE29-Aug-12 20:01
membercode cOmRAdE29-Aug-12 20:01 
GeneralMy vote of 5 Pin
Gun Gun Febrianza17-Aug-12 14:56
memberGun Gun Febrianza17-Aug-12 14:56 
Questionlove this article Pin
Gun Gun Febrianza17-Aug-12 14:56
memberGun Gun Febrianza17-Aug-12 14:56 
Questionc# webbrowser Pin
rakeshsavaliya18-Jul-12 22:31
memberrakeshsavaliya18-Jul-12 22:31 
QuestionProblem Pin
Member 898152618-Jul-12 12:29
memberMember 898152618-Jul-12 12:29 
QuestionDebugging Errors Pin
The_Boss11-Jul-12 13:06
memberThe_Boss11-Jul-12 13:06 
AnswerRe: Debugging Errors Pin
Member 1099615621-Jan-15 5:27
memberMember 1099615621-Jan-15 5:27 
BugSource code Pin
bionicman45218-Jul-12 23:47
memberbionicman45218-Jul-12 23:47 
QuestionFresher Pin
Member 77940401-Feb-12 22:12
memberMember 77940401-Feb-12 22:12 
GeneralMy vote of 5 Pin
Sergio Andrés Gutiérrez Rojas25-Jan-12 6:39
memberSergio Andrés Gutiérrez Rojas25-Jan-12 6:39 
QuestionUnhandled exception Pin
kmichaels20-Jan-12 2:47
memberkmichaels20-Jan-12 2:47 
AnswerRe: Unhandled exception Pin
mikejaeger21-Jan-12 2:43
membermikejaeger21-Jan-12 2:43 

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.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.151126.1 | Last Updated 20 Feb 2010
Article Copyright 2010 by Claudia Goga
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid