Using Internet Explorer in Your Applications


A common requirement of modern applications is to display HTML files and other files commonly used with Internet applications. Although the .NET Framework has considerable support for common image formats (such as GIF, JPEG, and PNG), working with HTML used to be a touch trickier in versions 1.0 and 1.1 of the .NET Framework. Life was made considerably easier with the inclusion of the WebBrowser control in the .NET Framework 2.0.

Important 

For information on how to accomplish this task using the .NET Framework 1.0 or 1.1, please review the second and third editions of this book.

You don’t want to have to write your own HTML parser, so using this control to display HTML pages is, in most cases, your only option. Microsoft’s Internet Explorer was implemented as a standalone component comprising a parser and a renderer, all packaged up in a neat COM object. The WebBrowser control “simply” utilizes this COM object. There’s nothing to stop you from using this COM object directly in your own applications, but it’s considerably easier to use the newer control for hosting Web pages in your applications.

Yes, a COM object. There is no managed version of Internet Explorer for use with .NET. Considering that writing an HTML parser is extremely hard, and writing a renderer is extremely hard, it’s easy to conclude that it’s much easier to use interop to get to Internet Explorer in the .NET applications than to have Microsoft try to rewrite a managed version of it just for .NET. Maybe we will see “Internet Explorer .NET” within the next year or two, but for now you do have to use interop.

Windows Forms and HTML - No Problem!

These sections demonstrate how to build a mini-browser application. Sometimes you might want to display HTML pages without giving users UI widgets such as a toolbar or the capability to enter their own URLs. You might also want to use the control in a nonvisual manner. For example, using the WebBrowser control, you can retrieve Web pages and then print the results without ever needing to display the contents. Let’s start, though, by first creating a simple form that contains only a TextBox and a WebBrowser control.

Allowing Simple Web Browsing in Your Windows Application

The first step is to create a new Windows Forms application called MiniBrowser. On the default form, place a single TextBox control and the new WebBrowser control, as shown in Figure 32-10.

image from book
Figure 32-10

The idea is that when the end user presses the Enter key (Return key), the URL entered in the text box will be the HTML page that is retrieved and displayed in the WebBrowser control. To accomplish this task, use the following code for your form:

  Public Class Form1     Private Sub TextBox1_KeyPress(ByVal sender As Object, _        ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress           If e.KeyChar = Chr(13) Then             WebBrowser1.Navigate(TextBox1.Text)         End If     End Sub End Class 

For this simple example, you check the key presses that are made in the TextBox1 control, and if the key press is a specific one - the Enter key - then you use the WebBrowser control’s Navigate() method to navigate to the requested page. The Navigate() method can take a single String value, which represents the location of the Web page to retrieve. The example shown in Figure 32-11 shows the Wrox website.

image from book
Figure 32-11

Launching Internet Explorer from Your Windows Application

Sometimes, the goal is not to host a browser inside the application but instead to allow the user to find the website in a typical Web browser. For an example of this task, create a Windows Form that has a LinkLabel control on it. For instance, you can have a form that has a LinkLabel control on it that simply states, “Visit your company website!”

Once this control is in place, use the following code to launch the company’s website in an independent browser, as opposed to directly in the form of your application:

  Public Class Form1    Private Sub LinkLabel1_LinkClicked(ByVal sender As System.Object, _       ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles _       LinkLabel1.LinkClicked         Dim wb As New WebBrowser         wb.Navigate("http://www.wrox.com", True)     End Sub End Class 

In this example, when the LinkLabel control is clicked by the user, a new instance of the WebBrowser class is created. Then, using the WebBrowser’s Navigate() method, the code specifies the location of the Web page as well as a Boolean value that specifics whether this end point should be opened within the Windows Form application (a False value) or from within an independent browser (a True value). By default, this is set to False. With the preceding construct, when the end user clicks on the link found in the Windows application, a browser instance is instantiated and the Wrox website is immediately launched.

Updating URLs and Page Titles

Note that when working with the MiniBrowser example in which the WebBrowser control is directly in the form, when you click the links, the text in the TextBox1 control is not updated. You can fix this by listening for events coming off the WebBrowser control and adding handlers to the control.

It’s easy to update the form’s title with the HTML page’s title. Create a DocumentTitleChanged event and update the form’s Text property:

  Private Sub WebBrowser1_DocumentTitleChanged(ByVal sender As Object, _    ByVal e As System.EventArgs) Handles WebBrowser1.DocumentTitleChanged     Me.Text = WebBrowser1.DocumentTitle.ToString() End Sub 

In this case, when the WebBrowser control notices that the page title has changed (due to changing the page viewed), the DocumentTitleChanged event will fire. In this case, you change the Form’s Text property (its title) to the title of the page being viewed using the DocumentTitle property of the WebBrowser control.

Next, update the text string that appears in the Form’s text box, based on the complete URL of the page being viewed. To do this, you can use the WebBrowser control’s Navigated event:

  Private Sub WebBrowser1_Navigated(ByVal sender As Object, _    ByVal e As System.Windows.Forms.WebBrowserNavigatedEventArgs) Handles _    WebBrowser1.Navigated     TextBox1.Text = WebBrowser1.Url.ToString()      End Sub 

In this case, when the requested page is finished being downloaded in the WebBrowser control, the Navigated event is fired. You simply update the Text value of the TextBox1 control to be the URL of the page. This means that once a page is loaded in the WebBrowser control’s HTML container, if the URL changes in this process, then the new URL will be shown in the text box. For example, if you employ these steps and navigate to the Wrox website (www.wrox.com), page’s URL will immediately change to http://www.wrox.com/WileyCDA/. This process also means that if the end user clicks on one of the links contained within the HTML view, then the URL of the newly requested page will also be shown in the text box.

Now, if you run the application with the preceding changes put into place, the form title and address bar will work as they do in Microsoft’s Internet Explorer, as demonstrated in Figure 32-12.

image from book
Figure 32-12

Creating a Toolbar

For this exercise, you’ll add a simple toolbar to the top of the control that gives you the usual features you’d expect from a Web browser - that is, Back, Forward, Stop, Refresh, and Home.

Rather than use the ToolBar control, you’ll add a set of button controls at the top of the control where you currently have the address bar. Add five buttons to the top of the control, as illustrated in Figure 32-13.

image from book
Figure 32-13

I’ve changed the text on the buttons to indicate their function. Of course, you can use a screen capture utility to “borrow” button images from IE and use those. The buttons should be named buttonBack, buttonForward, buttonStop, buttonRefresh, and buttonHome. To get the resizing to work properly, make sure that you set the Anchor property of the three buttons on the right to Top, Right.

On startup, buttonBack, buttonForward, and buttonStop should be disabled because there is no point to the buttons if there is no initial page loaded. You will later tell the WebBrowser control when to enable and disable the Back and Forward buttons, depending on where the user is in the page stack. In addition, when a page is being loaded, you need to enable the Stop button - but you also need to disable the Stop button once the page has finished being loaded.

First, though, you’ll add the functionality behind the buttons. The WebBrowser class itself has all the methods you need, so this is all very straightforward:

  Public Class Form1     Private Sub Form1_Load(ByVal sender As System.Object, _      ByVal e As System.EventArgs) Handles MyBase.Load         buttonBack.Enabled = False         buttonForward.Enabled = False         buttonStop.Enabled = False     End Sub     Private Sub buttonBack_Click(ByVal sender As System.Object, _      ByVal e As System.EventArgs) Handles buttonBack.Click         WebBrowser1.GoBack()         TextBox1.Text = WebBrowser1.Url.ToString()     End Sub     Private Sub buttonForward_Click(ByVal sender As System.Object, _      ByVal e As System.EventArgs) Handles buttonForward.Click         WebBrowser1.GoForward()         TextBox1.Text = WebBrowser1.Url.ToString()     End Sub     Private Sub buttonStop_Click(ByVal sender As System.Object, _      ByVal e As System.EventArgs) Handles buttonStop.Click         WebBrowser1.Stop()     End Sub     Private Sub buttonRefresh_Click(ByVal sender As System.Object, _      ByVal e As System.EventArgs) Handles buttonRefresh.Click         WebBrowser1.Refresh()     End Sub     Private Sub buttonHome_Click(ByVal sender As System.Object, _      ByVal e As System.EventArgs) Handles buttonHome.Click         WebBrowser1.GoHome()         TextBox1.Text = WebBrowser1.Url.ToString()     End Sub     Private Sub buttonSubmit_Click(ByVal sender As System.Object, _      ByVal e As System.EventArgs) Handles buttonSubmit.Click         WebBrowser1.Navigate(TextBox1.Text)     End Sub     Private Sub WebBrowser1_CanGoBackChanged(ByVal sender As Object, _      ByVal e As System.EventArgs) Handles WebBrowser1.CanGoBackChanged         If WebBrowser1.CanGoBack = True Then             buttonBack.Enabled = True         Else             buttonBack.Enabled = False         End If     End Sub     Private Sub WebBrowser1_CanGoForwardChanged(ByVal sender As Object, _      ByVal e As System.EventArgs) Handles WebBrowser1.CanGoForwardChanged         If WebBrowser1.CanGoForward = True Then             buttonForward.Enabled = True         Else             buttonForward.Enabled = False         End If     End Sub     Private Sub WebBrowser1_Navigated(ByVal sender As Object, _      ByVal e As System.Windows.Forms.WebBrowserNavigatedEventArgs) Handles _      WebBrowser1.Navigated         TextBox1.Text = WebBrowser1.Url.ToString()         Me.Text = WebBrowser1.DocumentTitle.ToString()     End Sub     Private Sub WebBrowser1_Navigating(ByVal sender As Object, _      ByVal e As System.Windows.Forms.WebBrowserNavigatingEventArgs) Handles _      WebBrowser1.Navigating         buttonStop.Enabled = True     End Sub     Private Sub WebBrowser1_DocumentCompleted(ByVal sender As Object, _      ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) _      Handles WebBrowser1.DocumentCompleted         buttonStop.Enabled = False     End Sub End Class 

Several different activities are occurring in this example, as there are so many options for the end user when using this MiniBrowser application. First, for each of the button Click events, there is a specific WebBrowser class method assigned as the action to initiate. For instance, for the Back button on the form, you simply use the Web Browser control’s GoBack() method. The same is true for the other buttons - for the Forward button you have the GoForward() method, and for the other buttons you have methods such as Stop(), Refresh(), and GoHome(). This makes it simple and straightforward to create a toolbar that provides actions similar to those of Microsoft’s Internet Explorer.

When the form is first loaded, the Form1_Load event disables the appropriate buttons. From there, users can enter a URL in the text box and click the Submit button to have the application retrieve the desired page.

To manage the enabling and disabling of the buttons, you have to key in a couple of events. As mentioned before, whenever downloading begins you need to enable Stop. For this, you simply add an event handler for the Navigating event to enable the Stop button:

 Private Sub WebBrowser1_Navigating(ByVal sender As Object, _  ByVal e As System.Windows.Forms.WebBrowserNavigatingEventArgs) Handles _  WebBrowser1.Navigating     buttonStop.Enabled = True End Sub

Next, the Stop button is again disabled when the document has finished loading:

 Private Sub WebBrowser1_DocumentCompleted(ByVal sender As Object, _  ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) _  Handles WebBrowser1.DocumentCompleted     buttonStop.Enabled = False End Sub

Enabling and disabling the appropriate Back and Forward buttons depends on the ability to go backward or forward in the page stack. This is achieved by using both the CanGoForwardChanged and the CanGoBackChanged events:

 Private Sub WebBrowser1_CanGoBackChanged(ByVal sender As Object, _  ByVal e As System.EventArgs) Handles WebBrowser1.CanGoBackChanged     If WebBrowser1.CanGoBack = True Then         buttonBack.Enabled = True     Else         buttonBack.Enabled = False     End If End Sub  Private Sub WebBrowser1_CanGoForwardChanged(ByVal sender As Object, _  ByVal e As System.EventArgs) Handles WebBrowser1.CanGoForwardChanged     If WebBrowser1.CanGoForward = True Then         buttonForward.Enabled = True     Else         buttonForward.Enabled = False     End If End Sub

Run the project now, visit a Web page, and click through a few links. You should also be able to use the toolbar to enhance your browsing experience. The end product is shown in Figure 32-14.

image from book
Figure 32-14

Showing Documents Using the WebBrowser Control

You are not limited to using just Web pages within the WebBrowser control. In fact, you can allow the end user to view many different types of documents. So far, you have seen how to use the WebBrowser control to access documents that have been purely accessible by defining a URL, but the WebBrowser control also enables you to use an absolute path and define end points to files such as Word documents, Excel documents, PDFs, and more.

For instance, suppose you are using the following code snippet:

  WebBrowser1.Navigate("C:\Financial Report.doc") 

This would open the Word document in your application. Not only would the document appear in the WebBrowser control, but the Word toolbar would also be present, as shown in Figure 32-15.

image from book
Figure 32-15

In Figure 32-16, the WebBrowser control shows an Adobe PDF file.

image from book
Figure 32-16

In addition to simply opening specific documents in the control, users can also drag and drop documents onto the WebBrowser control’s surface, and the document dropped will automatically be opened within the control. To turn off this capability (which is enabled by default), set the WebBrowser control’s AllowWebBrowserDrop property to False.

Printing Using the WebBrowser Control

Not only can users use the WebBrowser control to view pages and documents, they can also use the control to send these pages and documents to the printer for printing. To print the page or document being viewed in the control, simply use the following construct:

  WebBrowser1.Print() 

As before, it is possible to print the page or document without viewing it by using the WebBrowser class to load an HTML document and print it without even displaying the loaded document, as shown here:

  Dim wb As new WebBrowser wb.Navigate("http://www.wrox.com") wb.Print() 




Professional VB 2005 with. NET 3. 0
Professional VB 2005 with .NET 3.0 (Programmer to Programmer)
ISBN: 0470124709
EAN: 2147483647
Year: 2004
Pages: 267

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net