Page 1 of 1

Creating a simple web browser How to create a simple web browser using C# and WinForms

#1 PixelCard  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 47
  • View blog
  • Posts: 139
  • Joined: 20-June 08

Posted 10 July 2008 - 02:47 PM

In this tutorial I will show how to create a simple web browser application in C# using WinForms. I should mention, that in this project is used the WebBrowser control, which is a part of Internet Explorer. In this tutorial I also will use some XML, so you need at least a basic understanding of what it is.

Special Tutorial Requirements:
    * C# IDE (Visual Studio 2008 used in this tutorial)
    * .NET Framework 2.0

So, here we go.

1. Create a C# Windows Forms application:

Posted Image

2. Add a WebBrowser component to your form:

Posted Image

3. Change the WebBrowser control's Dock property to None:

Posted Image

4. Set the WebBrowser control's Anchor property to Top, Bottom, Left, Right (in this case the control will be resized with the form). As you see on the picture, it is set just to Top, Bottom, Right. This is because my form is resized only to the right, but you can change this property to other values as well.

Posted Image

5. Add a ToolStrip control to your form:

Posted Image

6. Add some buttons to the ToolStrip control (we'll need 5 buttons).

Posted Image

7. Set the DisplayStyle property of every added button to Text (you can change the style to one you like most).

8. Set the Text property of the buttons to the following:
  • <<BACK
  • FORWARD>>
  • REFRESH
  • STOP
  • HOME

9. Add a ListBox control to your form:

Posted Image

10. Anchor the ListBox control to Top, Right, Bottom:

Posted Image

11. Add a text field to the ToolStrip and a button with the Text property set to GO:

Posted Image

12. Change the Width property of the text field to 300 (so the URL can be fully viewable):

Posted Image

13. Add 2 buttons at the top of the ListBox (Add and Remove):

Posted Image

So, the form looks like this:

Posted Image


Now, let's pass to the code:


1. Declare the System.Xml namespace:

using System.Xml;



2. Declare the variable Home as string. It will keep the home page from the XML.

public string Home;



3. Code for the Form1_Load event:

// Creates a closing event for the form.
this.Closing += new CancelEventHandler(Form1_Closing);

listBox1.MouseDoubleClick += new MouseEventHandler(listBox1_MouseDoubleClick);
            XmlDocument loadDoc = new XmlDocument();
            loadDoc.Load(Application.StartupPath + "\\load.xml");
            Home = loadDoc.SelectSingleNode("/browser/home").Attributes["url"].InnerText;
            webBrowser1.Navigate(Home);

            foreach(XmlNode favNode in loadDoc.SelectNodes("/browser/favorites/item"))
                listBox1.Items.Add(favNode.Attributes["url"].InnerText);



The XML document is in the following format:

<browser>

<home url='http://www.dreamincode.net' />

<favorites>
<item url='www.ymail.com' />
<item url='www.dreamincode.net' />
</favorites>

</browser>



The file name is load.xml and the file is located in the same folder, as the executable. You can change the file path to the one you want. The ListBox is populated with favorites from the XML.

4. Code for the "<<BACK" button:

private void toolStripButton1_Click(object sender, EventArgs e)
        {
            webBrowser1.GoBack();

        }



5. Code for the "FORWARD>>" button:

private void toolStripButton2_Click(object sender, EventArgs e)
		{
			webBrowser1.GoForward();
		}



6. Code for the "REFRESH" button:

private void toolStripButton3_Click(object sender, EventArgs e)
        {
            webBrowser1.Refresh();
        }



7. Code for the "STOP" button:

 private void toolStripButton4_Click(object sender, EventArgs e)
        {
            webBrowser1.Stop();
        }



8. Code for the "HOME" button:


private void toolStripButton5_Click(object sender, EventArgs e)
        {
            webBrowser1.Navigate(Home);
        }



Remember I declared the Home variable as string? Now the browser will navigate to that URL if the "HOME" button is pressed.

9. The code for the listBox1_MouseDoubleClick (this event handler was declared in the Form1_Load event):

private void listBox1_MouseDoubleClick(object sender, EventArgs e)
        {
            if (listBox1.SelectedItem != null)
                webBrowser1.Navigate(listBox1.SelectedItem.ToString());
        }



10. The code for the "Add" button:

private void button1_Click(object sender, EventArgs e)
        {
            listBox1.Items.Add(webBrowser1.Url.OriginalString);
        }



11. The code for the "Remove" button:

private void button2_Click(object sender, EventArgs e)
        {
            // Removes the selected favorites entry.
            listBox1.Items.Remove(listBox1.SelectedItem);
        }



12. Now we need to program the Closing event of our form:

 private void Form1_Closing(object sender, CancelEventArgs e)
        {
XmlTextWriter writer = new XmlTextWriter(Application.StartupPath + "\\load.xml", null);

            writer.WriteStartElement("browser");
            writer.WriteStartElement("home");
            writer.WriteAttributeString("url", "http://www.dreamincode.net");
            writer.WriteEndElement();
            writer.WriteStartElement("favorites");
            for (int i=0; i < listBox1.Items.Count; i++ )
            {
                writer.WriteStartElement("item");
                writer.WriteAttributeString("url", listBox1.Items[i].ToString());
                writer.WriteEndElement();
            }
            writer.WriteEndElement();
            writer.WriteEndElement();
            writer.Close();
}



This one writes the stored favorites to the above mentioned load.xml using XmlTextWriter. If you look closer at the format of the file, you will see that this code writes the home page for our browser and every item in the favorites list (which is being parsed item-by-item).

Congratulations!
You've just created your own IE-based web browser!

Of course this tutorial shows only the basics of creating such kind of applications, but it gives an essential understanding on how the WebBrowser control works.

Attached File(s)



Is This A Good Question/Topic? 2
  • +

Replies To: Creating a simple web browser

#2 Kirth  Icon User is offline

  • D.I.C Head

Reputation: 9
  • View blog
  • Posts: 157
  • Joined: 09-July 08

Posted 11 July 2008 - 05:31 AM

Sorry if I'm wrong, but I think you forgot the code for the navigating itself!


 // Navigates to the given URL if it is valid.
        private void Navigate(String address)
        {
            if (String.IsNullOrEmpty(address)) return;
            if (address.Equals("about:blank")) return;
            if (!address.StartsWith("http://") &&
                !address.StartsWith("https://"))
            {
                address = "http://" + address;
            }
            try
            {
                webBrowser1.Navigate(new Uri(address));
            }
            catch (System.UriFormatException)
            {
                return;
            }
        }

        private void toolStripButton6_Click(object sender, EventArgs e)
        {
            webBrowser1.Navigate(toolStripTextBox1.Text);
        }




For the rest, nice tutorial with good and clearifying screenshots! Good work!
Was This Post Helpful? 1
  • +
  • -

#3 PixelCard  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 47
  • View blog
  • Posts: 139
  • Joined: 20-June 08

Posted 11 July 2008 - 12:32 PM

View PostKirth, on 11 Jul, 2008 - 05:31 AM, said:

Sorry if I'm wrong, but I think you forgot the code for the navigating itself!


 // Navigates to the given URL if it is valid.
        private void Navigate(String address)
        {
            if (String.IsNullOrEmpty(address)) return;
            if (address.Equals("about:blank")) return;
            if (!address.StartsWith("http://") &&
                !address.StartsWith("https://"))
            {
                address = "http://" + address;
            }
            try
            {
                webBrowser1.Navigate(new Uri(address));
            }
            catch (System.UriFormatException)
            {
                return;
            }
        }

        private void toolStripButton6_Click(object sender, EventArgs e)
        {
            webBrowser1.Navigate(toolStripTextBox1.Text);
        }




For the rest, nice tutorial with good and clearifying screenshots! Good work!


Thanks for reminding, because I really forgot about it.
Was This Post Helpful? 0
  • +
  • -

#4 halladayrules  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 25-November 08

Posted 25 November 2008 - 07:58 PM

Just needs some fine tuning my friend. Might I suggest adding the "Go" Button to the Accept button list so that when a user inputs "www.WHATEVER.com" and hits <enter> the enter button acts as a click event for the GO button and accesses the web page directly from pressing the enter button.
Was This Post Helpful? 0
  • +
  • -

#5 Guest_dfd*


Reputation:

Posted 15 March 2010 - 12:55 AM

How do i add the rules to the buttons ? i have not made a form with visual studio befor so i got no idea, do you just use @clickitem inside the code or do you click on the buttons and add it inthere could you explain that ?
Was This Post Helpful? 0

#6 Guest_guest*


Reputation:

Posted 15 March 2010 - 01:11 AM

how do you add new properties to listbox options ? i cant select anchor
Was This Post Helpful? 0

#7 Guest_guest*


Reputation:

Posted 15 March 2010 - 01:21 AM

i dont understand the anchor part :S
Was This Post Helpful? 0

#8 Janitor  Icon User is offline

  • D.I.C Head

Reputation: 6
  • View blog
  • Posts: 56
  • Joined: 30-July 10

Posted 16 November 2010 - 06:56 AM

//on click browse URL
        private void btnGo_Click(object sender, EventArgs e)
        {
            //declares URL as string variable
            string url = textBox1.Text;

            //if statment to determine if URL is correct
            if (url == "")
            {
                MessageBox.Show("Please Enter A Valid URL");
            }   
            
            //Corrects URL
            if (!url.StartsWith("https://") && !url.StartsWith("http://"))
            {
                url = "http://" + url;

                //navigates webBrowser to the URL
                webBrowser1.Navigate(url);
                
            }   
        }


Some users may find this useful. As not all people when navigating to a website use, http://, so this adds the Http:// & the WWW, to every URL - makes it easier when navigating...
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1