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

Using the WebBrowser control in .NET

By , 14 Mar 2002
 

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

About the Author

Nikhil Dabas
President NikSci
India India
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionHow get web browser displaying content height and width?memberkvnareshreddy4 Jul '11 - 22:50 
Hi,
how to get the web browser control content(not entire control) height and width?
Is it possible?
 
if not i want to set the height and width of the web browser control based on the content with out scroll bar...How to do it?
 
please any one tell me..
Generalnew simple web browser with geckofxmemberpukino18014 Apr '11 - 20:46 
http://webupon.com/browsers/how-to-create-simple-web-browser-gecko-c/[^]
Questionbookmarks, css..memberjaikishan j keswani16 Feb '11 - 5:02 
how to implement bookmarks, css support, scripts support etc..
QuestionHow can i display a RSS feed on a webbrowser control?memberToolzinho22 May '10 - 8:40 
How can i display a RSS feed on a webbrowser control? the only thing i'm getting is the tree view of the xml document, the so called feed source code. I just did something like
 

webbrowser.navigate(feed); //where feed as the url of the feed...
GeneralThank youmembernixiang13 May '10 - 15:34 
Thank you!
http://www.itwz.net
AnswerNeed to intercept a javascript window.close() event? [modified]memberMetalKid00724 Feb '10 - 9:14 
You can use this code to run code before the javascript pop-up of confirming the window close appears. However, if you do not close the form during this event, the pop-up will still come thru. My cancel code doesn't seem to abort the pop-up... Maybe someone else will have better luck with it.
 

public class ExtendedWebBrowser : WebBrowser
{
 
        public event EventHandler<CancelEventArgs> WindowClosing;
 

        /// <summary>
        /// Default constructor.
        /// </summary>
        public ExtendedWebBrowser()
        {
            // Nothing to do
        }
 
        /// <summary>
        /// Checks for a javascript window.close() message.
        /// </summary>
        /// <param name="m"></param>
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == 642 && m.WParam.ToInt32() == 1)
            {
                if (WindowClosing != null)
                {
                    CancelEventArgs e = new CancelEventArgs(false);
                    WindowClosing(this, e);
 
                    if (!e.Cancel)
                    {
                        base.WndProc(ref m);
                    }
                }
                else
                {
                    base.WndProc(ref m);
                }
            }
            else
            {
                base.WndProc(ref m);
            }
        }
 
    }
modified on Wednesday, February 24, 2010 3:21 PM

GeneralAdobe flash, shokwave addingmemberALEX CHIHAI13 Sep '09 - 4:25 
Hi there. I'm brandnew to c# Smile | :) so i need a little help here.
I am buiding a web brouser with the help of this code, but i can't figure out how to add some elements. Sniff | :^)
Please help me on this:
- Confused | :confused: how can i add some elements into this source to make flash player & shokwave elements aviabile for browsing?
Thanks... you're doing a great job man! Big Grin | :-D
QuestionHow to use IME in AXWebBrosermembercodemaster_ghaul24 Jun '09 - 23:36 
Hi,
 
My project is a plug-in to Visual Studio. I have a painter class inherits from SHDocVw.AxWebBrowser class and uses mshtml interfaces. Painter is used to create GUI elements. I am facing set of pblms when I use IME. I am getting all the IME related msges in IHTMLEventObj.PrehandleEvent like startcomposition, notify, IMERequest everything. But i'm not able to process anything within it. For eg. When I tried to get the current IME mode i'm not able to get it. When I try to use Microsoft's IME composition window it's not popping up.
Could you please let me know how to use IME in WebBrowser.
 

Sabaresh
QuestionGreat article, but I have one questionmemberRadu_2017 Dec '08 - 0:38 
Do you know how I can suppress the scroll bars? I want to display the page without the vertical and horizontal scroll bar.
 

Questionhow to disable browser information at the bottom when printing from a browser control C#memberSam Adah8 Oct '08 - 7:01 
Hello people, I need help.
 
I am developing an intranet app in C# with a broswer control. I would like to dis-able the bottom texts that appears whenever one is printing from a browser.
 
That is, at the bottom of a printed page from a website or a broswer you see something like this:
 
"http://127.0.0.1/somethingFolder/show?m=2.aspx   17/10/2008"
 
I want to be able to disble this function for my broswer in C# application.
 
Please i need your help guys..what should i do?
 
Thank you!

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130523.1 | Last Updated 15 Mar 2002
Article Copyright 2001 by Nikhil Dabas
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid