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, the 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 have 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.
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 platform provided 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 functions that you can learn from the
Windows Forms is also being used, but WPF is recommended nowadays.
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 ones 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
. Do not confuse with the System.Windows.Forms.WebBrowser
namespace
.
This ambiguity can cause you to be scratching your head and not understand why some controls, functions and properties are not found and 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 at 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 is either coming from some namespace
or you create it 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 at most 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:
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 (whereas 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. The 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
private void navigationKeys()
{
if (!myBrowser.CanGoForward)
{
BrowserGoForward.IsEnabled = false;
}
else
{
BrowserGoForward.IsEnabled = true;
}
if (!myBrowser.CanGoBack)
{
BrowserGoBack.IsEnabled = false;
}
else
{
BrowserGoBack.IsEnabled = true;
}
}
The 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()
{
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 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 browsers 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;
if (e.Key == Key.Enter)
{
try
{
myBrowser.Navigate(url);
}
catch (Exception er)
{
if (url.IndexOf("http://") == -1 || url.IndexOf("https://") == -1)
{
url = "http://" + url;
myBrowser.Focus();
try
{
myBrowser.Navigate(url.Replace("..", "."));
}
catch (Exception ex)
{
MessageBox.Show("The URL you provided is not correct, 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)
{
WebBrowser myBrowser = sender as WebBrowser;
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 conditions like these to add more features to this browser object.
Forward and Back Buttons
Every browser has a set of buttons 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:
private void BrowserGoBack_Click(object sender, RoutedEventArgs e)
{
if (myBrowser.CanGoBack)
{
myBrowser.GoBack();
}
}
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 buttons in the navigationKeys
event where these keys have been disabled if there is no webpage in the history where the user can surf to use 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 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:
private void BrowserRefresh_Click(object sender, RoutedEventArgs e)
{
myBrowser.Refresh();
myUrl.Text = myBrowser.Source.ToString();
}
Only the first line of code is required, the 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 spoke about and you can notice the WebBrowser
taking care of 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.
Events inside the WebBrowser
The events inside the WebBrowser
are handled by the Control
itself, you don't have to worry about them at all.
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.
I navigated to the Facebook website and the result was as follows:
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 code I have used and see how I 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 namespace
s 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
- 16th August, 2014: First version of the post