Using the WebBrowser Control from Visual Basic

Using the WebBrowser Control from Visual Basic


http://msdn.microsoft.com/workshop/browser/WebBrowser/WebBrowser.asp

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

An application can also create and manipulate an instance of the Internet Explorer application through OLE Automation with the InternetExplorer object. In this context, additional properties and methods not supported by the WebBrowser object are available. These additional features are indicated in the Applies To list for the InternetExplorer object only. If these features are used with the WebBrowser object, error codes will be returned. Errors can be trapped in Visual Basic with the "On Error Resume Next" statement and by accessing the Err object's associated properties such as Err.Number and Err.Description.

To implement the InternetExplorer object in a Visual Basic application, declare the object as indicated in the Application property description. To use the WebBrowser object, simply add the "Microsoft Internet Controls" to your Visual Basic project and place the WebBrowser control on a Visual Basic form. This is accomplished by selecting the "Components..." item on the Project menu in Visual Basic 5.0, or by selecting the "Custom Controls..." item on the Tools menu in Visual Basic 4.0.

Retrieving Information About the WebBrowser Control

Many properties can be used to retrieve information about the WebBrowser control. 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 current status of the WebBrowser control can be obtained using the Busy property. 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 an Internet Explorer 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 passed to the Navigate or Navigate2 method, you can optionally include flags to specify more detailed information about the navigation, such as the HTML frame name target and the HTTP headers sent to the server. You can browse 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 Explorer Options 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. When using OLE Automation, call the Quit method to close the instance of the Internet Explorer application.

The WebBrowser control triggers a number of different events to notify an application of user- and browser-generated activity. 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 Internet 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 flag that can be set to cancel the pending navigation request. This event can be useful for checking the requested URL against a database of unauthorized World Wide Web sites or local and network folders, and for canceling the navigation request. The WebBrowser control fires the NavigateComplete2 event after it has navigated to a new location. This event includes the same information as BeforeNavigate2, except NavigateComplete2 does not include the cancel flag.

Whenever the browser is about to begin a download operation, 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, often by displaying a progress bar. An application would 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 the new browser window or have a new instance of the Internet Explorer application created. Once the new window is created, an accompanying BeforeNavigate2 event occurs.

Note The events discussed in the preceding section that apply to the InternetExplorer object are supported in Visual Basic version 5.0 and later.

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 could create this simple application:

  1. Use the Navigate2 method to go to the desired HTML page during form loading.
    Private Sub Form_Load()
    	On Error Resume Next		'Don't stop execution, continue on next line
    	WebBrowser.Navigate2 "http:\\www.xyzcorp.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, ByVal Flags As Long, 
            ByVal TargetFrameName As String, PostData As Variant, ByVal Headers As String, 
            Cancel As Boolean)
        If (Instr(1,URL,"xyzcorp.com") = 0) And (Instr(1,URL,"C:") = 0) Then
            Cancel = True
            MsgBox "Access denied to URL: " & URL
        End If
    End Sub
    

Printing the Current Page with the WebBrowser Control

The WebBrowser control supports several 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 the implementation of a Print command button that, when clicked, checks to make sure the Print command is valid and then displays the print dialog box for the WebBrowser control.

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

	On Error Resume Next
	eQuery = WebBrowser1.QueryStatusWB(OLECMDID_PRINT)  'get print command status
	If Err.Number = 0 Then
    		If eQuery And OLECMDF_ENABLED Then
        		WebBrowser1.ExecWB OLECMDID_PRINT, OLECMDEXECOPT_PROMPTUSER, "", ""    'Ok to Print?
		  Else
        		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 as a guideline.

  1. Create a Standard EXE project in Visual Basic version 5.0.
  2. Select References under the Project menu, and add a reference to the "Microsoft Internet Controls" by checking the appropriate box. If this library is not available, you should browse for the Shdocvw.dll file.
  3. Select Add Class Module under the Project menu.
  4. In the General Declarations section of the class module, add this line of code:
    Public WithEvents m_oWbSink As SHDocVw.InternetExplorer
    
  5. At this point, you can select the m_oWbSink object in the left-hand object drop-down menu of the code window. 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 add the code to process the event. This example updates a text box on the form with the current browser status text.
    Private Sub m_oWbSink_StatusTextChange(ByVal Text As String)
        Form1.txtStatus.Text = Text
    End Sub
    
  6. Add the necessary declarations in the "General Declarations" section of the form, as follows:
    'Global reference to an instance of the browser
    Dim g_oIE As New SHDocVw.InternetExplorer
    'Global reference to an instance of a class that can sink the browser's events
    Dim g_oIESink As New Class1
    
  7. Now you can hook up the event sink to the instance of the browser by placing the following code in the form's "Form_Load" event:
    Set g_oIESink.m_oWbSink = g_oIE
    
  8. Finally, add any additional desired controls (buttons or text boxes, for example) and code to your project. Any events you need to use will be available in your newly created class module.

Note The preceding steps are unnecessary when using the WebBrowser object. Events are automatically trapped when you select the WebBrowser control in the Visual Basic toolbox and place it directly on a form.

© 1997 Microsoft Corporation. All rights reserved. Terms of Use.