Recipe 14.9. Using the New Web Browser ControlProblemYou need to display HTML-based content in a WinForms-based application. SolutionUse the System.Windows.Forms.WebBrowser class to embed web browser functionality into your application. The Cheapo-Browser seen in Figure 14-1 shows some of the capabilities of this control. Figure 14-1. The web browser controlWhile this is not a production quality user interface, it is called Cheapo-Browser for a reason. It can be used to select a web address, display the content, navigate forward and backward, cancel the request, go to the home page, add HTML directly to the control, print the HTML or save it, and finally enable or disable the context menu inside of the browser window. The WebBrowser control is capable of much more, but this recipe is meant to give you a flavor of what is possible. It would be well worth exploring its capabilities further to see what other needs it might fill. When you add your HTML (<h1>Hey you added some HTML!</h1>), it is displayed as shown in Figure 14-2. Figure 14-2. Adding HTML to the Cheapo-BrowserThe code to accomplish this is rather simple: this._webBrowser.Document.Body.InnerHtml = "<h1>Hey you added some HTML!</h1>"; The navigation to a web page is equally trivial: Uri uri = new Uri(this._txtAddress.Text); this._webBrowser.Navigate(uri); The nice thing about the navigation is the Navigated event that can be subscribed so you are notified when the navigation has completed. This allows code to spin this off in a thread and then come back to it once it is fully loaded. The event provides a WebBrowserNavigatedEventArgs class that has a Url property to tell the URL of the document that has been navigated to. private void _webBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e) { // Update with where we ended up in case of redirection // from the original Uri. this._txtAddress.Text = e.Url.ToString(); // Set up the buttons if we can go back or forth. this._btnBack.Enabled = this._webBrowser.CanGoBack; this._btnForward.Enabled = this._webBrowser.CanGoForward; } DiscussionIn the 1.x versions of the .NET Framework, embedding a web browser in your WinForms application was much more difficult and error-prone. With the advent of the 2.0 Framework, there is finally a .NET-based web browser control. You no longer have to struggle with some of the COM interop issues that could arise while trying to hook up to browser events. This is a good opportunity to make the line between your desktop and web applications blur even further and use the power of a rich client combined with web flexibility. See AlsoSee the "WebBrowser Class" topic in the MSDN documentation. |