Click here to Skip to main content
Click here to Skip to main content
Go to top

Using the WebBrowser control in .NET

, 14 Mar 2002
Rate this:
Please Sign up or sign in to vote.
Create a web browser completely in C#
<!-- Download Links -->

A Web Browser in C#

This article describes creating a web browser completely in C#. The application hosts a Microsoft WebBrowser Control and uses the functions it provides for all control. Here is a screenshot:

A lot of the functions do not work yet; most require some non-.NET programming to work. I stuck to pure .NET programming for this app, because it is meant to demonstrate features of the .NET Framework and not some APIs.

Building the Web Browser

Before you begin, you must generate some assemblies from the WebBrowser typlibs, so that they can be used in our code. Typlibs must be imported for:

  • The WebBrowser control itself, which is in SHDocVw.dll.
  • mshtml.tlb, if you plan to access the DHTML Object Model of the document.

This step is easy. At a command prompt, in a folder you create for this project, type:

aximp c:\windows\system\shdocvw.dll
tlbimp mshtml.tlb

The aximp command should generate two files: AxSHDocVw.dll and SHDocVw.dll. The tlbimp command should generate MSHTML.dll, which contains definitions for the DHTML DOM interfaces, along with about 3000 other types, so it might take a while to import.

Now you can proceed in several ways: You can do all coding by hand, or you can use Visual Studio.NET. I have done it the 'SDK way'. Basically, you have to create a form with:

  • The WebBrowser control itself.
  • A toolbar. Note that not all buttons on the toolbar work as you might expect them to.
  • A status bar. You can add panels for the status message, a progress bar, offline and secure icons, and a zone indicator. I've added these controls as placeholders only, they don't work (yet).
  • An address bar. This should be a panel with a label, a combo box, and a Go button.
  • A main menu for the application.
  • An image list for the toolbar.

Most of the initialisation code shall be added for you and little work needs to be done here. You must remember to add event handlers for the WebBrowser control, the status bar, the menus, the toolbar, the address combo box, and the Go button. All this code is present in the file WebBrowser.cs. In addition, extra dialogs are included in About.cs, ImportExport.cs, and Open.cs.

In the WebBrowser.cs file, you must put in the following statements in the namespace:

namespace ND.WebBrowser
{
  
  using System;
  using System.Drawing;
  using System.ComponentModel;
  using System.Windows.Forms;
  using Microsoft.Win32;
  using AxSHDocVw;
  using MSHTML;
  
  // etc..

Microsoft.Win32 is required because the application loads the URL MRU list from the registry. you can remove the MSHTML reference if you do not need it.

Notice SHDocVw is not included; this causes conflicts with the definitions in AxSHDocVw.dll. Most of the code is simple and calls functions of the WB control.

Menus and Toolbars

The menu and the toolbar are standard Windows Forms stuff. Menu popup events are handled to update the enabled/disabled and checked state of menu items. For example:

protected void mnuFile_Popup(object sender, EventArgs e)
    {
      MenuItem miFile = MenuMain.MenuItems[0];
      miFile.MenuItems[14].Checked = AxWebBrowser.Offline;
      
      Int32 EnabledTest = Convert.ToInt32(SHDocVw.OLECMDF.OLECMDF_SUPPORTED)
          + Convert.ToInt32(SHDocVw.OLECMDF.OLECMDF_ENABLED);
      
      miFile.MenuItems[2].Enabled = EnabledTest.Equals(AxWebBrowser.QueryStatusWB //Refresh test for Edit
        (SHDocVw.OLECMDID.OLECMDID_REFRESH));
      miFile.MenuItems[3].Enabled = EnabledTest.Equals(AxWebBrowser.QueryStatusWB
        (SHDocVw.OLECMDID.OLECMDID_SAVE));
      miFile.MenuItems[4].Enabled = EnabledTest.Equals(AxWebBrowser.QueryStatusWB
        (SHDocVw.OLECMDID.OLECMDID_SAVEAS));
      miFile.MenuItems[6].Enabled = EnabledTest.Equals(AxWebBrowser.QueryStatusWB
        (SHDocVw.OLECMDID.OLECMDID_PAGESETUP));
      miFile.MenuItems[7].Enabled = EnabledTest.Equals(AxWebBrowser.QueryStatusWB
        (SHDocVw.OLECMDID.OLECMDID_PRINT));
      miFile.MenuItems[8].Enabled = EnabledTest.Equals(AxWebBrowser.QueryStatusWB
        (SHDocVw.OLECMDID.OLECMDID_PRINTPREVIEW));
      miFile.MenuItems[13].Enabled = EnabledTest.Equals(AxWebBrowser.QueryStatusWB
        (SHDocVw.OLECMDID.OLECMDID_PROPERTIES));
    }

First, the File menu object is obtained. Then the WB control is used to check the enabled status of commands in the menu. If you are familiar with COM programming, this should be standard code. Otherwise, read the WebBrowser control documentation at MSDN: WebBrowser. Most commands are also executed in the standard COM IOleCommandTarget way, like this:

    protected void mnuFileSave_Click(object sender, EventArgs e)
    {
      Object o = null;
      m_axWebBrowser.ExecWB(SHDocVw.OLECMDID.OLECMDID_SAVE,
        SHDocVw.OLECMDEXECOPT.OLECMDEXECOPT_DODEFAULT,
        ref o, ref o);
    }

A null object reference is passed for the input and output arguments of the ExecWB method. Simply because we have no arguments to pass. Some menu commands use methods of the WebBrowser control itself, like Home and Search. The other source files have other dialogs, like the Import & Export dialog.

protected void mnuFileOpen_Click(object sender, EventArgs e)
    {
      OpenForm frmOpen = new OpenForm();
      frmOpen.ShowDialog(this);
      if(frmOpen.DialogResult == DialogResult.OK)
      {
        Object o = null;
        AxWebBrowser.Navigate(frmOpen.Address, ref o, ref o, ref o, ref o);
      }
    }

The Import and Export dialog uses the ShellUIHelper object, documented at MSDN: Shell Helper API.

Editing the Document

Instead of calling an external editor, all editing is done by the WebBrowser control itself, using an IE 4 feature which allows documents to make themselves editable. However, our code only invokes the edit mode, and does nothing beyond that.

protected void mnuFileEdit_Click(object sender, EventArgs e)
    {
      IHTMLDocument2 doc;
      object boxDoc = AxWebBrowser.Document;
      doc = (IHTMLDocument2)boxDoc;
      doc.designMode = "On";
    }

The code first gets a reference to the Document object and then unboxes it to get to the IHTMLDocument2 interface. This is necessary because the WebBrowser control returns the document as an object and not an IHTMLDocument2 pointer.

The Finished Code

That just about sums up most of the code. However, a lot of things do not work yet. Here is a short list:

  1. 'Full Screen' and 'View Source' in the application menus.
  2. Enumeration of the user's Favourites and History.
  3. 'Send' submenu of 'File' menu.
  4. Mail button on toolbar.
  5. Edit works to only to a limited extent.
  6. Tools Menu.
  7. Back and Forward drop-downs.
  8. Some pages, especially those with frames, do not load properly. ( ? )
  9. There is no handling for new windows.
  10. Status bar icons (secure, offline, zone) are not displayed.

Most code should be easy to create, and can be done within the .NET Framework. However, some functions, like those for favourites and history, shall involve PInvoke.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Nikhil Dabas
President NikSci
India India
No Biography provided

Comments and Discussions

 
Questionsae PinmemberMember 1021470613-Sep-13 0:37 
QuestionHow get web browser displaying content height and width? Pinmemberkvnareshreddy4-Jul-11 22:50 
Generalnew simple web browser with geckofx Pinmemberpukino18014-Apr-11 20:46 
Questionbookmarks, css.. Pinmemberjaikishan j keswani16-Feb-11 5:02 
QuestionHow can i display a RSS feed on a webbrowser control? PinmemberToolzinho22-May-10 8:40 
GeneralThank you Pinmembernixiang13-May-10 15:34 
AnswerNeed to intercept a javascript window.close() event? [modified] PinmemberMetalKid00724-Feb-10 9:14 
GeneralAdobe flash, shokwave adding PinmemberALEX CHIHAI13-Sep-09 4:25 
QuestionHow to use IME in AXWebBroser Pinmembercodemaster_ghaul24-Jun-09 23:36 
QuestionGreat article, but I have one question PinmemberRadu_2017-Dec-08 0:38 
Questionhow to disable browser information at the bottom when printing from a browser control C# PinmemberSam Adah8-Oct-08 7:01 
GeneralAvoid WebBrowser Address Bar Cache Dynamic Link History ! [modified] Pinmemberkelvin199717-Feb-08 1:26 
I see quite a few server->client applications trying to Avoid WebBrowser Address Bar Cache Dynamic Link History !
e.g. remove this one www.myserver.com/users/login.aspx?id=2324&adz=534
 
WE USE WEB BROWSER CONTROL: -------------------------------
Some server->client applications try to use webBrowser to read, process and respond dynamic web pages. It makes life easier.
webBrower control takes the default settings from IE. So you don't have to worry about Proxy Settings, Firewalls and all that.
As long as IE can go on to Internet that means your application can go on Internet too.
e.g.
client side app navigates to the server side:
www.myserver.com/users/login.aspx?id=2324&adz=534
 
that way the client side app you wrote will automatically login for client id=2324 and give that client some advertisement id=534
 
sameway, you can do:
www.myserver.com/users/recordAction.aspx?id=2324
 
so your server side app records some client activity sent from the client side.
 
WEB BROWSER PROBLEM: -------------------------------------------
you will notice when you type in IE (Internet Explorer Program on your computer desktop) address bar "www.myserver.com" the whole lot of dynamic links you use as commands with parameters appears
e.g.
login.aspx?id=2324&adz=534
recordAction.aspx?id=2324
No, you don't want them appear in the address bar because you don't want the user to find out all your secret commands and/or parameter IDs.
So what do you do? Deleting the unwanted cache from history is rather difficult. Many people got stuck here.
 
SOLVING THE PROBLEM: -------------------------------
1. You could use System.Web.HttpRequest... but you have to rewrite a large part of your app and as I mentioned earlier you need to take care of Proxy and stuff. Na...
 
2. Using Web Service. I tried this before. same login at server side, same code, one written as ASPX page, the other one modified to ASMX. I realised that ASPX responded almost instantly. The web service ASMX took about 20-30 seconds to initialise the login. Microsoft website explains that ASMX needs to init for the 1st time, once the session has started it will be as fast as ASPX page. However, that init login being fast is exactly what I need. So, hmm...na...I personally do not like web service either.
 
3. Here is the real deal. You CAN stick with your webBrowser control.
Calling MyBrowser.Navigate("http://www.myserver.com/users/login.aspx?id=2324&adz=534") will leave a cache in your IE history telling everyone the login ID and all that.
 
To AVOID THAT you can do the following:
 
Dim myuri As New Uri("http://www.myserver.com/users/login.aspx")
Dim loginInfo As String = "id=2324&adz=534"
Dim postdata() As Byte = System.Text.ASCIIEncoding.ASCII.GetBytes(loginInfo)
MyBrowser.Navigate(myuri, Nothing, postdata, "User-Agent: MyBrowser")
 
At server side, you read the post data as plain text. you will pick up the text "id=2324&adz=534" parse it yourself.
Postdata will not leave dynamic link parameters in history. Further more, check UserAgent at server side. It will pervent normal browsers from attempting to browse your magic commands. You can redirect them to somewhere else if user agent is not MyBrowser.
 
Hope I can help some people here Big Grin | :-D
 
modified on Monday, February 25, 2008 2:51 AM

QuestionTo protect web page PinmemberMateenDeshmukh14-Feb-08 20:44 
GeneralRe: To protect web page Pinmemberkelvin199717-Feb-08 0:38 
AnswerRe: To protect web page [modified] Pinmemberkelvin199717-Feb-08 0:46 
QuestionRe: To protect web page PinmemberMateenDeshmukh28-Feb-08 20:13 
AnswerRe: To protect web page PinmemberMicael Gustavsson11-Nov-08 21:34 
GeneralaxWebBrowser/WebBrowser Pinmemberdon_32027-Nov-07 13:51 
Questionhow to supress upload /download option in axwebbrowser via this mshtml document class Pinmembervilasinivils21-Aug-07 21:05 
QuestionWebBrowser by winform in linux PinmemberSaumya127-Aug-07 1:12 
GeneralEmbed file xls (excel 2007) in C# (vs 2005) PinmemberRoberto.ec2-Aug-07 13:35 
QuestionHow to add delay Pinmemberkzfid25-Jul-07 3:36 
Questionhow to record ajax/applet data from an object Pinmembernumpsy b29-Jun-07 3:03 
Generalneed help Pinmembersuperda29-May-07 4:07 
GeneralGreat article - but a word of caution... PinmemberBarry M.4-May-07 5:03 
Questionbrowser toobar Pinmembermitjee18-Apr-07 23:57 
QuestionPage cannot display?? PinmemberSandeep B.8-Apr-07 20:58 
GeneralCaching problem Pinmemberjk_just22-Feb-07 19:53 
Questionhow to get the html element and its value when clicked PinmemberMystic_7-Feb-07 7:32 
AnswerRe: how to get the html element and its value when clicked Pinmemberjesuscheung19-Mar-07 4:18 
GeneralRe: how to get the html element and its value when clicked PinmemberMystic_19-Mar-07 4:33 
GeneralRe: how to get the html element and its value when clicked Pinmemberjesuscheung19-Mar-07 4:43 
GeneralRe: how to get the html element and its value when clicked PinmemberMystic_19-Mar-07 4:54 
AnswerRe: how to get the html element and its value when clicked Pinmembersouidi abderrahmen11-Nov-09 2:17 
QuestionHow could I control the navigation to be in just one session? PinmemberPar Witch11-Jan-07 3:16 
QuestionAxWebBrowser Navigate Problem Pinmembertaiqi28-Nov-06 11:41 
GeneralAccess WebBrowser control's encoding menu programmatically PinmemberVikbol25-Oct-06 3:30 
GeneralRe: Access WebBrowser control's encoding menu programmatically Pinmembermshon5-Mar-07 11:30 
QuestionFavourites Pinmemberzulbaric20-Oct-06 1:03 
Questionhow to handle onclick event on the Browser component PinmemberMystic_30-Sep-06 20:43 
QuestionProblem with AxWebBrowser.Document Pinmembertrupci23-Jul-06 21:26 
QuestionSome warning messages during TLBimp... should i panic? Pinmemberbebangs22-Jun-06 16:17 
Generalhmmm Pinmembersorinceldesteptrau8-Jun-06 0:17 
GeneralError Loading Page Pinmemberfari_far27-May-06 18:36 
Questionaximp command doesn't work Pinmemberlulaleila2-May-06 7:18 
AnswerRe: aximp command doesn't work PinmemberNikhil Dabas2-May-06 8:34 
GeneralRe: aximp command doesn't work Pinmemberwolffighters1-Oct-06 14:11 
Generalporting to asp.net Pinmember_kane_19-Mar-06 21:24 
GeneralRe: porting to asp.net Pinmemberkap21-Mar-06 23:36 
Questionstopping pop-ups Pinmemberbhandari.amit18-Feb-06 2:45 

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 | Mobile
Web03 | 2.8.140916.1 | Last Updated 15 Mar 2002
Article Copyright 2001 by Nikhil Dabas
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid