14.8. Using the Web Browser Control
Problem
You need to display HTML-based content in a WinForms-based application.
Solution
Use 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 control
While 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 for-ward 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 taste 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-Browser
The 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); ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access