Export (0) Print
Expand All
21 out of 61 rated this helpful - Rate this topic

Reusing the WebBrowser Control

The WebBrowser control adds browsing, document viewing, and data downloading capabilities to your applications. Applications using this control will allow the user to browse sites on the Internet's World Wide Web, as well as folders in the local file system and on a network. The WebBrowser control supports Web browsing through both point-and-click hyperlinking and URL navigation. The control maintains a history list that allows the user to browse forward and backward through previously browsed sites, folders, and documents.

Note   For the Microsoft .NET Framework version of this control, see WebBrowser Control (Windows Forms).

This topic contains the following sections.


The WebBrowser control implements navigation, hyperlinking, history lists, favorites, and security. It acts as a container for the MSHTML component, an Active document (also known as a DocObject) that can display HTML. The MSHTML component exposes the Dynamic HTML (DHTML) object model, hosts Microsoft ActiveX controls and script languages, and parses and renders HTML. See Reusing MSHTML for details about directly hosting the MSHTML component.

Applications can also use the WebBrowser control to host Active documents other than MSHTML. This means that richly formatted documents, such as Microsoft Excel spreadsheets or Microsoft Word documents, can be opened and edited in place from within the WebBrowser control.

security note Security Alert   In Microsoft Internet Explorer 6 or later, the WebBrowser control is no longer marked "safe for scripting" when it is hosted in Windows Internet Explorer or when it is hosted in the Internet security zone. Use an iframe as an alternative to the WebBrowser control; it provides a browsable container that is both scriptable and secure.

Using the WebBrowser Control from Visual Basic

This section describes the basics of using the WebBrowser control in Microsoft Visual Basic, including:

WebBrowser Control Basics

The WebBrowser control supports properties, methods, and events that allow developers to create a highly customized browser with the WebBrowser object. For example, you can use the WebBrowser control to create a Web browsing application that restricts navigation to a local intranet and company-approved public Web sites.

To use the WebBrowser object, simply add the "Microsoft Internet Controls" component to your Visual Basic project and place the WebBrowser control on a Visual Basic form. Add the component library by selecting Components on the Project menu in Visual Basic, or by right-clicking the project in Microsoft Visual Studio 2005 and choosing the Add Reference... option on the context menu.

An application can also create and manipulate an instance of the Internet Explorer application through Automation with the InternetExplorer object. To launch Internet Explorer from a Visual Basic application, first declare the object, then navigate it, and finally display it (make it visible) as follows:

Dim objIE As SHDocVw.InternetExplorer
Set objIE = CreateObject("InternetExplorer.Application")
objIE.Visible = True 

The WebBrowser object does not support all the properties and methods that are available to the InternetExplorer object. To determine if a feature is supported, refer to the "Applies To" list on the reference page for each method or property. Some InternetExplorer features return error codes if they are invoked by the WebBrowser object. (In Visual Basic, you can trap errors with the "On Error Resume Next" statement and by accessing the Err object's associated properties, such as Err.Number and Err.Description.)

Retrieving Information About the WebBrowser Control

Many WebBrowser properties return information about the control. Here are a few examples.

  • The LocationName and LocationURL properties can be used to retrieve information about the location that is currently displayed. If the location is an HTML page on the World Wide Web, LocationName retrieves the title of that page, and LocationURL retrieves the URL of that page. If the location is a folder or file on the network or local computer, LocationName and LocationURL both retrieve the Universal Naming Convention (UNC) name or the full path of the folder or file.

  • The Busy property returns the current status of the WebBrowser control. This Boolean value indicates whether the control is engaged in a navigation or downloading operation. You should check the value of this property before issuing the Stop method to cancel navigation or downloading operations.

Customizing the User Interface

The WebBrowser control supports properties and associated events to manipulate various user interface elements of the InternetExplorer application or a custom browser. The size and position of the window used by the WebBrowser control can be read or set with the Height, Left, Top, and Width properties. Other user interface elements are enabled with individual properties such as MenuBar, FullScreen, StatusBar, and ToolBar. The associated OnMenuBar, OnFullScreen, OnStatusBar, and OnToolBar events are triggered when the property value changes. These events return a Boolean value to indicate the new state of the property and to provide a mechanism to respond to user actions in the InternetExplorer object.

When using OLE Automation with the InternetExplorer object, the application window can be shown or hidden by setting the value of the Visible property. When changed, the associated OnVisible event returns the current Boolean value of the property. You may also want to retrieve information about the Internet Explorer application itself. To do so, use the Name property to get the Internet Explorer application name, and use the Path and FullName properties to get the Internet Explorer application's path and file name.

Navigating with the WebBrowser Control

Use the Navigate (or Navigate2) method to browse HTML pages on the World Wide Web or any file or folder on the network or local computer. In addition to the required URL argument, you can optionally include flags to specify more detailed information about the navigation, such as the named frame or window target and the http headers sent to the server. You can move through the sites maintained in the browser's history list during each browser session by using the GoBack and GoForward methods. If you wish to go directly to the Internet Explorer home or search pages that have been specified in the Internet Properties dialog box, use the GoHome or GoSearch method. To display the most current version of a page the browser is viewing, use the Refresh or Refresh2 method respectively. When using OLE Automation, call the Quit method to close the instance of the Internet Explorer application.

The WebBrowser control fires a number of different events to notify an application of activity generated by the user and browser itself. When the browser is about to navigate to a new location, it triggers a BeforeNavigate2 event that specifies the URL or path of the new location and any other data that will be transmitted to the Web server through the HTTP transaction. The data can include the HTTP header, HTTP post data, and the URL of the referrer. The BeforeNavigate2 event also includes a Cancel flag that can be set to halt the pending navigation request. This event can be useful for checking the requested URL against a database of unauthorized Web sites or local and network folders, and for canceling or redirecting the navigation request. The WebBrowser control fires the NavigateComplete2 event after it has successfully navigated to a new location. This event includes all the same information as BeforeNavigate2 except the Cancel flag.

Whenever the browser is about to download a Web page or file from the Internet, it triggers the DownloadBegin event. The control also generates a number of ProgressChange events as the operation progresses, and then it triggers the DownloadComplete event after completing the operation. Applications typically use these three events to indicate the progress of the download operation. An application might show the progress bar in response to DownloadBegin, update the progress bar in response to ProgressChange, and hide the progress bar in response to DownloadComplete.

When an application calls the Navigate (or Navigate2) method with the navOpenInNewWindow flag, the NewWindow2 event occurs before the new browser window is created. This event allows the application to create its own new browser window or allow a new instance of the Internet Explorer application to be created. Once the new window is created, an accompanying BeforeNavigate2 event occurs.

Creating a Custom Browser with Limited Functionality

Suppose you want to create a custom browser application to start and display an HTML page that is not the user's home or start page. You also want the custom browser to navigate only to HTML pages on the local domain or view files on the local hard disk. Here's how you might create this simple application:

  1. Use the Navigate2 method to go to the desired URL during form loading.
    Private Sub Form_Load()
        On Error Resume Next		'Don't stop execution, continue on next line
        WebBrowser.Navigate2 "http://www.contoso.com"
        If Err.Number <> 0 Then MsgBox "Error :" & Err.Description	'Display error message
    End Sub
  2. Check the URL in the BeforeNavigate2 event to make sure the location string contains the local domain or disk. If the location string doesn't meet the criteria, cancel the operation and display an error message to the user.
    Private Sub WebBrowser_BeforeNavigate2(ByVal URL As String, ByRef Flags As Long, _
            ByRef TargetFrameName As String, ByRef PostData As Variant, _
            ByRef Headers As String, ByRef Cancel As Boolean)
        If (InStr(1,URL,"contoso.com") = 0) And (InStr(1,URL,"C:") = 0) Then
            MsgBox "Access denied to URL: " & URL
            Cancel = True
        End If
    End Sub
security note Security Alert   Parsing the URL string for protocol and domain name is a nontrivial and error-prone task. Oversimplified code, like the preceding example, can easily be tricked into allowing the user to view resources that the developer did not wish to make available. A more complete solution should be able to parse and validate components of the URL.

The Framework version of the WebBrowser control automatically converts the URL string into a Uri object. The following example reworks the simple implementation above to provide improved URL detection and control.

Private Sub WebBrowser_Navigating(ByVal sender As System.Object, _
        ByVal e As System.Windows.Forms.WebBrowserNavigatingEventArgs) _
        Handles WebBrowser.Navigating
    If Not (e.Url.Host.Contains("contoso.com") Or e.Url.IsFile) Then
        MsgBox("Access denied to URL: " & e.Url.ToString())
        e.Cancel = True
    End If
End Sub 

Printing the Current Page with the WebBrowser Control

The WebBrowser control supports common file operations (such as Print, Print Preview, Save, Save As, New, and Properties) with the QueryStatusWB and ExecWB methods. These methods directly access the IOleCommandTarget interface for issuing commands on the Active document or inquiring about which commands it supports. The following example shows one possible implementation of a Print command button that, when clicked, checks to make sure printing is enabled before it displays the Print dialog box for the WebBrowser control.

Private Sub BtnPrint_Click()
    Dim eQuery As SHDocVw.OLECMDF       'return value type for QueryStatusWB

    On Error Resume Next
    eQuery = WebBrowser.QueryStatusWB(SHDocVw.OLECMDID.OLECMDID_PRINT)  'get print command status
    If Err.Number = 0 Then
        If eQuery And SHDocVw.OLECMDF.OLECMDF_ENABLED Then
            WebBrowser.ExecWB(SHDocVw.OLECMDID.OLECMDID_PRINT, _
                    SHDocVw.OLECMDEXECOPT.OLECMDEXECOPT_PROMPTUSER, "", "")    'Ok to Print?
            MsgBox("The Print command is currently disabled.")
        End If
    End If
    If Err.Number <> 0 Then MsgBox("Print command Error: " & Err.Description)
End Sub 

Capturing Events with the InternetExplorer Object

When using OLE Automation to control a separately running instance of an application, you will need to create a mechanism to respond to events triggered by that ActiveX object. To create this mechanism, commonly referred to as an event sink, use the following steps (written in Visual Basic .NET) as a guideline.

Note  The following steps are unnecessary when using the WebBrowser object. Events are routed automatically when you select the WebBrowser control in the Visual Basic toolbox and place it directly on a form.
  1. Create a "Standard EXE" project in Visual Basic .NET.
  2. Add a multi-line text box to the main form called txtStatus to capture status events.
  3. Select Add References... under the Project menu, and add a COM object reference to the "Microsoft Internet Controls."
  4. Under the Project menu, select Add Class.... Click OK to create Class1. Any events you need to use will be available in your newly created class module.
  5. Add the following member variables and class constructor:
    Dim WithEvents m_oIE As SHDocVw.InternetExplorer
    Dim m_oParent As Form1
    Public Sub New(ByVal oParent As Form1)
        m_oParent = oParent
    End Sub
  6. At this point, you can use the left-hand object drop-down menu of the code window to select the m_oIE object. After selecting this object, the right-hand procedure drop-down window lists all of the events supported by this object. Select one of the events, and then add the code to process the event. This example updates the multi-line text box on the main form with the current browser status text.
    Private Sub m_oIE_StatusTextChange(ByVal Text As String) _
            Handles m_oIE.StatusTextChange
        If (Text <> Text.Empty) Then
            m_oParent.txtStatus.AppendText(Text + vbCrLf)
        End If
    End Sub
  7. To access the encapsulated instance of Internet Explorer from the main form, add a Navigate method to your class.
    Public Sub Navigate(ByVal txtAddress As String)
        If m_oIE Is Nothing Then
            m_oIE = New SHDocVw.InternetExplorer
        End If
        If (m_oIE.Busy) Then m_oIE.Stop()
        m_oIE.Visible = True
    End Sub
  8. If the browser is closed by the user, the application's instance of InternetExplorer will no longer be valid and should be released. You can do this in the OnQuit event.
    Private Sub m_oIE_OnQuit() Handles m_oIE.OnQuit
        m_oIE = Nothing
    End Sub 
  9. In the main form, add the following variable declaration:
    Dim m_oIESink As Class1
  10. Finally, hook up the event sink to the instance of the browser by placing the following code in the form's Form_Load event:
    m_oIESink = New Class1(Me)

When the browser is navigated, the status events are captured to the multi-line text box on the main form.

Using the WebBrowser Control from C/C++

This section describes some common implementations of the WebBrowser control in C/C++, including:

WebBrowser Control Basics

One of the most common uses for the WebBrowser control is to add Internet browsing functionality to your application. Using the IWebBrowser2 interface, you can browse to any location in the local file system, on the network, or on the World Wide Web. You can use the IWebBrowser2::Navigate method to tell the control which location to browse to. The first parameter is a string that contains the name of the location. To browse to a location in the local file system or on the network, specify the full path to the file system location or the UNC name of the location on the network. To browse to a site on the World Wide Web, specify the URL of the site.

The IWebBrowser2::Navigate method allows you to target a specific frame on an HTML page, causing the WebBrowser control to display a Web site or file system location in that frame. First, you would call the IWebBrowser2::Navigate method and specify the URL of an HTML page that contains a frame. Then, by specifying the name of the frame in subsequent calls to IWebBrowser2::Navigate, you can direct the control to display subsequent locations within that frame.

By including a text box in your application, you can let the user specify the location to browse to and then pass the location to the IWebBrowser2::Navigate method. You can also retrieve information about the resource that is currently displayed. If the location is an HTML page, IWebBrowser2::get_LocationName retrieves the title of that page, and IWebBrowser2::get_LocationURL retrieves the URL of that page. If the location is a folder or file on the network or local computer, these methods both retrieve the UNC or full path of the folder or file.

Adding Internet Browsing Functionality to Your Application

To add the WebBrowser control to a basic Microsoft Foundation Classes (MFC) application, perform the following steps.

  1. Right-click the Project name, and point to Add, the select Class... from the context menu.
  2. Select "MFC Class From ActiveX Control" and click Add.
  3. Select "Microsoft Web Browser" from among the classes listed in the registry. Highlight the IWebBrowser2 interface, and click the right arrow to generate a new CWebBrowser2 class.
  4. Click Finish.

With the new class added to the project, you can dynamically create the control in the OnCreate handler of the application's view class. The following code assumes you have added a m_pBrowser member variable to the view.

int CChildView::OnCreate(LPCREATESTRUCT lpCreateStruct)
    // Create the control.
    m_pBrowser = new CWebBrowser2;
    ASSERT (m_pBrowser);
    if (!m_pBrowser->Create(NULL, NULL, WS_VISIBLE, CRect(0,0,0,0), this, NULL))
        TRACE("failed to create browser\n");
        delete m_pBrowser;
        m_pBrowser = NULL;
        return 0;
    // Initialize the first URL.
    COleVariant noArg;
    CString strURL("www.microsoft.com");
    m_pBrowser->Navigate(strURL, &noArg, &noArg, &noArg, &noArg);
    return 0;

Finally, move the control to cover the desired area in the OnSize handler. Remember to use a NULL background brush when registering the view window class to prevent screen flicker when the WebBrowser control is resized.

void CChildView::OnSize(UINT nType, int cx, int cy)
    m_pBrowser->MoveWindow(0, 0, cx, cy);

Printing Pages with the WebBrowser Control

Although the WebBrowser control does not support a print method, you can print its contents using one of the following methods:

  • Send the WebBrowser control a key combination of CTRL+P.
  • Retrieve the IOleCommandTarget interface of document, and execute OLECMDID_PRINT, as follows:
    LPDISPATCH pDisp = m_pBrowser->get_Document();
        pDisp->QueryInterface(IID_IOleCommandTarget, (void**)&pCmdTarg);
            // Print contents of WebBrowser control.

Changing Text Size with the WebBrowser Control

In Internet Explorer, you can increase or decrease the size of the text from the View menu, but the WebBrowser control does not have a method to do this. Instead, the control exposes this functionality through the IOleCommandTarget interface of the document. Call IOleCommandTarget::Exec with OLECMDID_ZOOM and pass a value in the range of 0 to 4 (where 0 is smallest) to indicate the desired scale of the font.

LPDISPATCH pDisp = m_pBrowser->get_Document();
    pDisp->QueryInterface(IID_IOleCommandTarget, (void**)&pCmdTarg);
        COleVariant vaZoomFactor;   // input argument
        V_VT(&vaZoomFactor) = VT_I4;
        V_I4(&vaZoomFactor) = fontSize;   // 0 - 4

        // Change the text size.



Working with WebBrowser Events

Note   You will need to implement an event sink to capture and handle events. An example of how to implement an event sink for DWebBrowserEvents2 can be found in the Objvw sample.

The WebBrowser control fires a number of different events to notify an application of user—and browser—generated activity. The events are implemented using the DWebBrowserEvents2 interface. When the control is about to navigate to a new location, it fires a DWebBrowserEvents2::BeforeNavigate2 event that specifies the URL or path of the new location and any other data that will be transmitted to the Internet server through the http transaction. The data can include the http header, http post data, and the URL of the referrer. DWebBrowserEvents2::BeforeNavigate2 also includes a Cancel flag that you can set to FALSE to cancel the navigation. The WebBrowser control fires the DWebBrowserEvents2::NavigateComplete2 event after it has navigated to a new location. This event includes the same information as DWebBrowserEvents2::BeforeNavigate2, but DWebBrowserEvents2::NavigateComplete2 does not include the Cancel flag.

When the WebBrowser control is about to begin a download operation, it fires the DWebBrowserEvents2::DownloadBegin event. The control fires a number of DWebBrowserEvents2::ProgressChange events as the operation progresses, and then it fires the DWebBrowserEvents2::DownloadComplete event after completing the operation. Applications typically use these three events to indicate the progress of the download operation, often by displaying a progress bar. An application would show the progress bar in response to DWebBrowserEvents2::DownloadBegin, update the progress bar in response to DWebBrowserEvents2::ProgressChange, and hide it in response to DWebBrowserEvents2::DownloadComplete.

When an application calls the IWebBrowser2::Navigate method with the Flags parameter set to navOpenInNewWindow, the WebBrowser control fires the DWebBrowserEvents2::NewWindow2 event before navigating to the new location. The event also includes a Cancel flag and a pointer that can receive a new browser window, if you prefer to create one of your own. If not, the event fires as normal, and opens a new InternetExplorer object to handle the navigation.

Related Topics

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

© 2014 Microsoft. All rights reserved.