Integrating Web Browser with WPF Forms
Posted by Igor Moochnick on 12/24/2007
There are so many situations where you need to render an HTML in your forms. It may happen when you’d want, for example, to show an external web page, feed or a locally generated content like XML or an HTML. The Web Browser is extremely handy for the Web Automation (I’ll talk about it in future posts) since you have full HTML DOM available for control at your fingertips. So, having WPF now out there is not changing a thing – it’s still possible to host Web Browser inside a form.
Look how easy it is. Let’s say you want to show your blog on an application form. To do so:
- Create a WPF application with a Form.
- From the toolbox drop a WindowsFormsHost on the form. Give it a name, let’s say, “windowsFormsHost”. Make sure that the references to the WindowsFormsInteroperability and System.Windows.Forms were added to your project. To make a better presentation make the Margin = 0 – the control will fill in all the available form’s space.
- In the XAML source add “Loaded” attribute with “Window_Loaded” value to the tag.
- Add the following code to the Window_Loaded handler in the .cs file:
WebBrowser wb = new WebBrowser(); wb.Navigate(ConfigurationManager.AppSettings["Feed"]); windowsFormsHost.Child = wb;
Build, run and enjoy!