1. Introduction to C# WebBrowser Control
The ‘C# WebBrowser Control’ provides the capability of browsing the web pages to our application. One can also display their own HTML content through the web browser control. That means he/she can generate all fancy reports in html content and then display that in a WebBrowser Control. In this example, we will explore how to design simple browsing window. Note, even though this example acts as a browser, when you are browsing using this sample, do not provide any sensitive information. This is just a sample that shows the use of WebBrowser Control. At the end, we will also explore how to display the user content with button click and hook that to the C# handler method.
2. About This C# WebBrowser Control Example
The screen shot of the C# WebBrowser Control Example is shown below:
The user will type the web address in the Address Bar. To navigate to the web address, the user should click the ‘Go’ button. The ‘Stop’ and ‘Reload’ do the same job as every browser are doing today. When the sample is navigating and consuming the web content, the progress bar shows how much it progressed the current load content. The information bar shows what part of the page content is getting loaded. When you run this C# WebBrowser Control Example, you may notice for downloading a page, there may be multiple navigation start. Moreover, each start and end pair denote the browser may need to download the contents from the different locations to construct the page fully. Now we will implement the example.
The buttons UserCont1 and UserCont2 helps you to understand hooking the html forms with windows form. For example, a button in html invoking a function is C#.
3. Setting Up WebBrowser Control
The browser example we will create here is the combination of ToolStrip, StatusStrip, and the WebBrowser control. First, we create the toolbar, and then place the required controls on the toolbars. Below video shows how to set up the toolbar:
Video 1: Toolbar Setup
In the above video, we will not see the buttons for user content. We will add that later. Next, we should add the StatusStrip control to the example. After adding StatusStrip Control to the form, we add a Progress bar and a label for displaying the information. This is shown in the below video:
Video 2: Status Bar Setup
Finally, we added the C# WebBrowser Control to our sample. Note that when we place the WebBrowser control on the form, it occupies the entire free area in which we drop it. The below video shows it:
Video 3: Place WebBrowser Control on the Form
Tags for coding: //WEB_BR, //WEB_CS
WEB_BR: Coding shows some basic WebBrowser supports.
WEB_CS: Coding shows displaying the user content and handling the control events from those scripts.
4. WebBrowser Page Navigate
C# WebBrowser control provides rich functionalities, and, in this Example, we will see the basic actions like loading a web page, stopping the current page load and refreshing the page load. Then, we will explore how to load custom java script and handle event raised by it in C# through the WebBrowser Control.
In the Go button click handler, we take the web address in the Address box and navigate to that page. In the meantime, we display the status text, ‘Loading’. The
Navigate
method will absorb web content from the web address specified by the user and displays that in the WebBrowser control.
1 2 3 4 5 6 |
private void btnGo_Click(object sender, EventArgs e) { //Web_BR 01: Navigate to the URL Browser.Navigate(txtTBURL.Text); Status_Information.Text = "Loading..."; } |
Cancelling the page load and refreshing the loaded/partly loaded page contents are straight forward. We should call the relevant methods in the WebBrowser Control. Below are the handler functions for Stop and Reload buttons.
1 2 3 4 5 6 7 8 9 10 11 |
private void btnStop_Click(object sender, EventArgs e) { //Web_BR 02: Stop Loading the Page Browser.Stop(); } private void btnReload_Click(object sender, EventArgs e) { //Web_BR 03: Refresh the Page Browser.Refresh(); } |
5. Page Navigation Progress
When we load a web page on a browser, to load the full document, the browser may navigate to many web locations. Say, for example, the website having a lot of YouTube embedded videos and review about the video which is page’s own content. Let us also assume the web page contains a ‘Facebook Likes’. When we browse to that web page, the browser will load the review content of the video from the page itself, then it navigates to the YouTube and Facebook to get other required information. So, to load a full document to the browser, it should navigate to three web addresses even though the user specifies only one address in the address bar of the sample browser.
When the browser is navigating to a site to load some portion of the document, we will get two events
<strong>Navigating Event</strong>
and
Navigated Event
. The first event says that the navigation is about to start, and the second event says navigation is done. We get the
DocumentCompleted Event
once after browser loaded the complete web page. We handled all the three events to display the status information:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
private void frmWebBrowser_Load(object sender, EventArgs e) { //Web_BR 04: Hide the visibility of the status bar Status_PB.Visible = false; } private void Browser_Navigating(object sender, WebBrowserNavigatingEventArgs e) { //Web_BR 06: Provide some information about the //current navaigation Status_PB.Visible = true; Status_Information.Text = "Navigating " + e.Url.ToString() + " for " + e.TargetFrameName; } private void Browser_Navigated(object sender, WebBrowserNavigatedEventArgs e) { //Web_BR 07: Provide some information about the //current navaigation Status_Information.Text = "Navigated.."; } private void Browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { //Web_BR 08: Provide some information about the //current navaigation Status_PB.Visible = false; Status_Information.Text = "Web Page Loaded"; } |
Note, we hide the progress bar in the status strip during the form load and we enable that when the Browser starts its first navigation for the page. Once we receive the
DoumentCompleted
Event, we again disable the progress bar. Below given video shows loading the web page in our browser sample:
Video 4: C# WebBrowser Control – Page Navigation & Its Progress in
6. Custom HTML Script With Button
When we click the custom button 1 from the tool strip, the browser loads custom script 1. The script has an HTML button in it. The C# WebBrowser Control will hook this HTML Button Click event with a handler function in C#. This happens in runtime and hence the writer of the HTML Script do not know which C# Method will handle the Click Event.

C# WebBrowser Control – User Defined Scripts
We revise the ToolStrip of our browser sample application to have two more buttons and each button loads two different user contents in the WebBrowser control. The below video shows how to add these two buttons to the ToolStrip control:
Video 5: Add Two More Buttons to ToolStrip Control
After adding the extra buttons to the StatusStrip, we will create the Custom HTML scripts using visual studio. Below is the formatted HTML content:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<html > <head> <title>Button Click by ID</title> </head> <body> The button placed below is a html button. The button is accessed by C# and a handler method(in C#) is provided at runtime <input id='BtnTest' style='z-index: 100; left: 8px; width: 102px; position: absolute;top:60px' type='button' value='button'/> </body> </html> |
In the above script, we gave an Id (
BtnTest
) to the
Input
tag. In addition, we specify the control type as a button using the value attribute. Notice that we don’t have click event and handler for this HTML button. At runtime, our browser example will get this button from the loaded HTML content, and dynamically hooks the C# handler to the HTML button click. Video 6 shows creating and formatting the HTML shown above using the visual studio IDE.
Video 6: Creating HTML Content Using Visual Studio IDE
Note that we changed the double quotes as single quotes. This will avoid formatting the HTML content when we assign it as a string to the WebBrowser control later.
7. C# Handler For HTML Button Click
7.1 Declaring Script Flag
In the above script, the HTML Designer not aware of which function to call when the user clicks the button. Our C# WebBrowser control decides that at runtime. The first thing we should do is adding a private flag customDoc1. We will set this flag when the WebBrowser control is loading the user HTML script.
1 2 |
//Web_CS 01: Declare boolean tag for document 1 and 2 private bool customDoc1 = false; |
7.2 Loading User Script
The
DocumentText
property of the browser control is used to load a document. In the button click handler (For the first user script), we gave the above-created user content 1 to the WebBrowser control by setting this
DocumentText
Property.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
//Web_CS 02: Place the Html document with a button having proper Id private void btnUser1_Click(object sender, EventArgs e) { //Setting this property will load the document and //raise DocumentCompleted Event Browser.DocumentText = "<html ><head><title>" + "Button Click by ID</title></head><body>The button placed" + " below is a html button. The button is accessed by C# and a " + "handler method(in C#) is provided at " + "runtime<input id='BtnTest' " + "style='z-index: 100; left: 8px; width: 102px; " + "position: absolute;top:60px' " + "type='button' value='button'/></body></html>"; customDoc1 = true; } |
7.3 Hooking HTML Click Event With A C# Method
We gave the new content for the WebBrowser control by setting the
DocumentText
property. Now, the WebBrowser control will load the HTML content and after the load, it will fire the
DocumentCompleted
event. In the event handler, we get the HTML button by calling
GetElementById
function and passing the button id as an argument. We store the return value of the function as ‘
HtmlElement
’. At last, we hook the click event of the button element to a C# function using the delegate ‘
HtmlElementEventHandler
’.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
//Web_CS 03: Get the Html button from the loaded document // Script. Then attach the C# method as click handler if (customDoc1 == true) { //03.1 : Get html Element HtmlElement btnElem = Browser.Document.GetElementById("BtnTest"); //03.2 : Hook the C# method to the event if (btnElem != null) btnElem.Click += new HtmlElementEventHandler(Html_test_button_Hanlder); //03.3 : Reset the Tag customDoc1 = false; } |
7.4 C# Handler Function
The handler function for the html button click is shown below:
1 2 3 4 5 6 |
//Web_CS 04: Create a button handler for Html Button void Html_test_button_Hanlder(object sender, HtmlElementEventArgs evArg) { MessageBox.Show("Click event of the Script button Handled"); } |
In this section, we created an HTML content with a button in it. Then we loaded the HTML content into the WebBrowser control. Once the user content is loaded completely, we get the HTML button instance from the loaded document and attached c-sharp method as its click event handler. Here, the person who designs the HTML document is not aware of the c-sharp handler. Sometimes, the HTML script knows which function to call on the c-sharp code library. In that case, the html script developer will provide the click handler during the HTML design itself. We will see that in the next section.
8. C# WebBrowser & HTML Script – Example 2
Look at the second custom script shown below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<html > <head> <title> Button Click Hooked to External Method of C# </title> </head> <body>The scripting person knows which c# function to call. So the well known c# method is tied in the OnClick Attribute <input style='z-index: 100; left: 8px; width: 102px; position: absolute;top: 44px' type='button' onclick='window.external.ShowMessageE()' value='button'/> </body> </html> |
In this script, we do not define the input button with the id. In the
OnClick
event, the handler function
external.ShowMessageE
is specified as an event handler. The external here specifies that the function
ShowMessageE()
is available from the external source. In our case, the external source is C# as the WebBrowser control will load this script.
8.1 Include Required Namespace
In the Web browser sample, first, we included the required namespace. This is to make the class ‘HtmlSupportingMethods’ that we will implement soon as a COM visible class.
1 2 |
//Web_CS 05: Declare the required namespace using System.Runtime.InteropServices; |
8.2 Load 2nd HTML Script
In the button click, we specify the second user content through the DocumentText property of WebBrowser Control. The control loads the document the same way it loaded our first script. The only difference is, here we used the verbatim string (@stringcontent) to keep the format of the string as it is.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
//Web_CS 06: Set the Html as document content of the browser control. private void btnUser2_Click(object sender, EventArgs e) { string htmldoc = @"<html> <head> <title> Button Click Hooked to External Method of C# </title> </head> <body>The scripting person knows which c# function to call. So the well known c# method is tied in the OnClick Attrubite <input style='z-index: 100; left: 8px; width: 102px; position: absolute;top: 44px' type='button' onclick='window.external.ShowMessageE()' value='button'/> </body> </html>"; //Setting this property will load the document and raise //document completed Browser.DocumentText = htmldoc; } |
8.3 Handler Method & COM Visible Class
The class
HtmlSupportingMethods
has only one public method, which is linked by our custom script 2 as
Window.external.ShowMessageE()
. As the external scripting world calls this method, we mark the containing class as COM compatible by marking the class with the
[ComVisible(true)]
attribute.
1 2 3 4 5 6 7 8 9 10 11 12 |
//Web_CS 07: External scripting methods. This class is set with //the ComVisible attribute as it's methods are going to be accessed //by the html document content that will be loaded by the //Web Browser control [ComVisible(true)] public class HtmlSupportingMethods { public void ShowMessageE() { MessageBox.Show("External Method Accessed"); } } |
8.4 Linking The Script With C# Class
There is one final step. How does the HTML content loaded on the WebBrowser control knows where to find the External Source? We should link our
HtmlSupportingMethods
with the HTML script paving a path to ShowMessageE. The
ObjectForScripting
property takes instance of our
HtmlSupportingMethods
so that HTML scripting get access to the public scoped
ShowMessageE
method. We do that in the form load as shown below:
1 2 |
//Web_CS 08: Set the Scripting Object. This should a com visible object Browser.ObjectForScripting = new HtmlSupportingMethods(); |
The below video shows our final testing of the WebBrowser Control Example. The video shows both the user HTML documents and hooking the HTML button click to C# code.
Video 7: Testing the scripting support
Source Code : Download C# WebBrowser Control Example From Google Drive
- Dynamically Changing ASP.Net Web Config File
- Auto Commit, Implicit & Explicit SQL Transactions Explained
Categories: C#
Tags: DocumentCompleted Event, DocumentText Property, HtmlElementEventHandler, Navigate() Method, Navigated Event, Navigating Event, ObjectForScripting, Refresh() Method, Stop() method