Programming Examples

Are you a Programmer or Application Developer or a DBA? Take a cup of coffee, sit back and spend few minutes here :)

C# WebBrowser Control Explained

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:

C# WebBrowser Control Example

C# WebBrowser Control Example

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.

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.

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:

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

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:

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.

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.

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

’.

7.4 C# Handler Function

The handler function for the html button click is shown below:

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:

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.

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.

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.

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:

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

Categories: C#

Tags: , , , , , , , ,

Do you like this Example? Please comment about it for others!!

This site uses Akismet to reduce spam. Learn how your comment data is processed.