Click here to Skip to main content
Click here to Skip to main content

Creating a custom Web Browser using .NET's WebBrowser Control

, 16 Aug 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
How to use the .NET's WebBrowser control in your application to create a custom Web Browser for Windows OS.

Introduction

This article explains the WebBrowser control of the WPF (Windows Presentation Foundation; not to be confused with the Windows Forms WebBrowser control, they're not alike) and its basic usage in your software to create a basic Web Browser application in your .NET software. 

Background

Back when I started to learn how to develop a software I tried to look at a sample Browser application and I was not able to understand the code, since that was too buggy and not understandable for me. 

2 months ago same thing happened, and another developer was looking for the same thing to develop a web browser that would run on Windows OS and so I tried to write the application and share it on the web so that others can also understand how to write a simple C# program to create a Web Browser. 

Environment Requirements

This project was developed using .NET Framework 4.5 and Visual Studio 2013. You need to be having Visual Studio 2013. You can get your copy of Visual Studio from Microsoft, you can either try it or buy it. 

You can get an Express copy of Visual Studio for free from Microsoft's MSDN library's download tab. 

http://msdn.microsoft.com/developer-resource-downloads-msdn

Once done, you can continue to download the project and build it using your Visual Studio. 

Understanding the WPF

WPF is a model by Microsoft, where you can focus on the C# code and logic and forget about the UI code to settle the UI and other codes that you had to do in Windows Form and even in C++'s Win32 applications. 

A quote from the MSDN about WPF is as:

Windows Presentation Foundation (WPF) provides developers with a unified programming model for building rich Windows smart client user experiences that incorporate UI, media, and documents.

WPF includes a set of UI controls that you can use in your Windows's software and moreover control them using C# code from the backend. You can find the list of controls that you can use in from MSDN where they provide you with the basics about the control and they provide you with the methods and properties of the controls. 

WPF was developed after Windows Forms, to minimize the problems that developers had to face in Windows Forms and is the latest programming platfrom povided by the Microsoft. 

http://msdn.microsoft.com/en-us/library/ms754130(v=vs.110).aspx

WPF allows you to design the Layout, control the data binding with the data and more function that you can learn from the 

Windows Forms is also being used, but WPF is recommended now adays.

Understand the WebBrowser control

There is a difference between the WebBrowser control of Windows Forms and the WPF WebBrowser control. Some of the methods and properties were removed from the WebBrowser control and some new were added to it which were better and merging properties caused it to be less in size but more in power. 

You can get the documentation about the WebBrowser control that I am using in this article from the System.System.Controls.WebBrowser namespace. Donot confuse with the System.Windows.Forms.WebBrowser namespace.

http://msdn.microsoft.com/en-us/library/system.windows.controls.webbrowser(v=vs.110).aspx

This ambiguity can cause you to be scratching your head and not understand why some controls functions and properties are not found an the Visual Studio is complaining for some assembly. Visual Studio tries to look for the properties of the Control inside the namespace class you've already added in the Solution in the top of your source code like this

using System.Windows.Controls;

..now when you will access it, using the following constructor 

WebBrowser myBrowser = new WebBrowser();

..it will provide you with the instance of the browser from the WPF WebBrowser and not the Windows Forms WebBrowser since you're not using that namespace and the functions in that WebBrowser will not be found in this instance. That is why Visual Studio complains that the following function was not found and something like that. 

So keep in mind that each and every object that you access in your software are either coming from some namespace or you create them yourself. The functions they perform are also coming from the same source they're coming from.

Writing code for the Application

You can create a simple Visual C# progam and write the code to it, to make it a Web Browser application for yourself, the code atmost uses the WebBrowser class object and just updates the UI. The remaining thing is handled by the WebBrowser Control itself, so you don't have to work with every child object inside the document etc. 

Creating the WebBrowser object (XAML)

Once you've created a WebBrowser object inside the XAML, you just have to worry about the stuff outside of it, and not the inside of it. The XAML code for the WebBrowser that we're using is like this

<WebBrowser Name="myBrowser"  
            Height="530" 
            Margin="0, 55, 0, 0"
            KeyDown="myBrowser_KeyDown" 
            Navigating="myBrowser_Navigating"
            Navigated="myBrowser_Navigated"
            LoadCompleted="myBrowser_LoadCompleted"
            />

There are some events attached to this WebBrowser that we will discuss in the coming paragraphs.

MainWindow constructor

Like all other programs, our Main function is the creation of the MainWindow instance, whose constructor in our software is as

// MainWindow class constructor
public MainWindow()
{
     InitializeComponent();

     myBrowser.Navigate("http://www.google.com");
     myUrl.Text = "http://www.google.com";

     ChangeUserAgent("Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");
     uri = "http://www.google.com";

     this.setView();
     this.navigationKeys();
}

In the constructor, I am changing the User-Agent of the browser to make websites think that the browser requesting for the data is IE9 (where as it is not). After this, inside the constructor I am calling two other functions that need to be called at the starting point to settle the navigation keys and the view of the browser. Above code is just the code that is executed when the application starts, you can attach other methods to this constructor to execute them as soon as the application starts. 

Navigation Keys handler event

// The navigation keys settings
private void navigationKeys()
{
     // if browser has a forward page
     if (!myBrowser.CanGoForward)
     { 
         // enable button
         BrowserGoForward.IsEnabled = false;
     }
     else
     {
         // disable it
         BrowserGoForward.IsEnabled = true;
     }
     
     // if browser has a back page
     if (!myBrowser.CanGoBack)
     {
         // enable button
         BrowserGoBack.IsEnabled = false;
     }
     else
     {
         // disable button
         BrowserGoBack.IsEnabled = true;
     }
}

Above control buttons are from XAML, they're written there and I am calling this code to enable or disable them.

View setting event handler

The view setting event as in the constructor, is written as

private void setView() 
{
     // this code sets the height and the width of the WebBrowser element.
     myBrowser.Width = this.Width;
     myBrowser.Height = (this.Height - 59);
}

This is a small piece of code and you can even understand it by just watching at it. This sets the width and the height of the Browser Control relative to the MainWindow. Here in this code, this refers to the MainWindow class.

Handling the Key Events inside the Browser

Every browser has some keyboard functions defined that the user can use to do the tasks without having to use the mouse. Most of the browser have different function, but most functions are alike and are defined in the Browser to be handled by the software. 

Our browser has some functions like what would happen if the user presses backspace key, what if user presses enter key while typing a URL inside the TextBox provided to him. For that, in the WebBrowser we have defined a function for the KeyDown, and in the C# code we can handle it easily.

private void myUrl_KeyDown(object sender, KeyEventArgs e)
{
     TextBox textBox = sender as TextBox;
     string url = textBox.Text;

     // get if the key is ENTER key and then navigate
     if (e.Key == Key.Enter)
     {
         try
         {
             myBrowser.Navigate(url);
         }
         catch (Exception er)
         {
             // there was an error in the URI, complete it!
             if (url.IndexOf("http://") == -1 || url.IndexOf("https://") == -1)
             {
                 // there was no URI indicator, append it to string!
                 url = "http://" + url;
                 myBrowser.Focus();
                 try
                 {
                     myBrowser.Navigate(url.Replace("..", "."));
                 }
                 catch (Exception ex)
                 {
                     MessageBox.Show("The URL you provided is not corrent, check it twice.");
                 }
                 myUrl.Text = myBrowser.Source.ToString();
             }
         }
     }
}

The above code handles all the events in the browser that trigger the KeyDown event but only tries to work for them where the condition is met. You can think of the BACKSPACE key event like this

private void myBrowser_KeyDown(object sender, KeyEventArgs e)
{
     // get the web browser
     WebBrowser myBrowser = sender as WebBrowser;

     // get if the key is BACKSPACE then go back!
     if (e.Key == Key.Back)
     {
         if (myBrowser.CanGoBack)
         {
             myBrowser.GoBack();
         }
     }
}

This way, you can minimize the chances of the issues of exception if there is no back page. You check for the back page, if browser can go back then go back otherwise leave the event. 

You can add more of these conditions like these to add more features to this browser object.

Forward and Back buttons

Every browser has a set of button that deal with the browser's history, and surf forward or go backwards in the history. Our browser has native buttons that deal with this feature and we've got them covered in the navigationKeys handler events. But to see them how they actually work, we can use this code

// Back button handler, loads previous page in history (if present)
private void BrowserGoBack_Click(object sender, RoutedEventArgs e)
{
    if (myBrowser.CanGoBack)
    {
        myBrowser.GoBack();
    }
}

// Forward button handler, loads next page in history (if present)
private void BrowserGoForward_Click(object sender, RoutedEventArgs e)
{
     if (myBrowser.CanGoForward)
     {
         myBrowser.GoForward();
     }
}

You can easily get to the point what this code does. It goes backward or forward if there is any webpage in the history and so on. This is the maximum code required to create these buttons and this checks the condition and would not throw any kind of error, since we're navigating if there is any page otherwise will do nothing. An extra layer of security has been added to these button in the navigationKeys event where these keys have been disabled if there is no webpage in the history where the user can surf to using these buttons. 

Refreshing the Web Browser (page)

You can add a refresh page functionality to the browser too, it is also a single line code but a worth noting since almost every browser must have these functions. Not all of the users know the Keyboard shortcuts so they use the UI to interact with the software application. So we would do the very same thing here, the code for the refresh is 

// Reload the current page function.
private void BrowserRefresh_Click(object sender, RoutedEventArgs e)
{
    myBrowser.Refresh();
    myUrl.Text = myBrowser.Source.ToString();
}

Only the first line of code is required, second line of code just updates the URL bar's value. 

Using the Software to test

You can now use the Software to test the Web Browser application and you can notice the changes that I have spoke about and you can notice the WebBrowser taking care of itself on itself. 

Running the Software

This depends on whether you create the software and then run it, or you debug it. 

The first page that you will see is the main page (homepage) that has been set to Google's main page. 

Main Page (Google Homepage)

Events inside the WebBrowser

The events inside the WebBrowser are handled by the Control itelf, you don't have to worry about them at all. 

Events inside the Control

You can see that you didn't have to worry at all about the events of the object itself, they're handled automatically. You just have to write the code about the software application.

Navigating to another webpage

Like all other web browsers our web browser has a URL bar where users can add the URL they want to move on to but remember in the real code, you need to be having the URI written as: "http://www.example.com", simple "example.com" won't work. But in this browser I have captured this error and allowed the user to just write the domain name.

URL eitor

I navigated to the Facebook website and the following was the result, 

Facebook page

Full screen (Maximized)

The maximized view of the Browser is something like above, you can use both the views but remember, to always capture the event and then resize it. You can see the events in the codes I have used and see how I have changed the view of the WebBrowser on each WindowResize event. 

Points of Interest

I learnt that in every namespace each object can be named differently but there can be names of the class objects in other namespaces that match. You must call the very name of the object and then you can use the properties and functions attached to it. Otherwise you won't get the software to work.

History

First Version of the post.

License

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

Share

About the Author

Afzaal Ahmad Zeeshan
Student De Codes
Pakistan Pakistan
Hi, my name is Afzaal Ahmad Zeeshan. I am a Pakistani, student, Ahmadi Muslim kid. I live in Rabwah and I am here since I was ~3years old. I have done my matriculation with major subjects for Science and Intermediate in Engineering.
 
I started learning programming when I was 15 and wrote small application that would get me double (not the data type) of the int value I would provide it with. In the beginning, I started Web applications, using ASP.NET when I was 16 and I really didn't know ASP.NET is written in C#, all I knew was that there is something called Razor syntax. I created simple web applications like Say hello to a friend, Add a friend in your list and get the elder among them. After craming the ASP.NET codes, I finally realized that there is no way to write application by cramming the API. So, I went learning, I learnt Visual C#, Java, Visual C++, started to learn Assembly but gave up in the middle, will restart this.
 
I have written some projects for my friends, I have made some web applications for cousins, I have developed a few applications for my cell phone, for desktop. I have developed an HTML keyboard for websites, like a On-Screen Keyboard, A Login system using simple C# code and JSON files. I am planning to write a Database system that would be much much much less costly than MS SQL. I am author at many blogs and teach programming to new developers to the extent that I have learnt programming.
 
I am never found complaining, I am self teaching, I am polite to elders, I accept my mistakes without criticizing the person who found a bug in me. I listen to Eminem, more than I listen to my girl. I am logical, you can make me quite my logically proving me wrong. Otherwise our dicussion might be a never ending loop.
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
BugMissing Namespace PinmemberTed Goulden18-Aug-14 18:27 
AnswerRe: Missing Namespace PinprofessionalAfzaal Ahmad Zeeshan19-Aug-14 5:02 
GeneralRe: Missing Namespace PinmemberTed Goulden19-Aug-14 9:34 
AnswerRe: Missing Namespace PinprofessionalAfzaal Ahmad Zeeshan19-Aug-14 10:38 
GeneralMy vote of 3 Pinmemberdjmarcus18-Aug-14 7:55 
AnswerRe: My vote of 3 PinprofessionalAfzaal Ahmad Zeeshan19-Aug-14 5:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    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
Web01 | 2.8.141220.1 | Last Updated 16 Aug 2014
Article Copyright 2014 by Afzaal Ahmad Zeeshan
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid