C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
In a WPF program, we provide access to websites (and other data sources) with the WebBrowser control. WebBrowser uses the Internet Explorer rendering engine.
Example. Please first drag a WebBrowser control from the Toolbox to your WPF window. You will want to expand the WebBrowser to fit the window. Now, add a Name attribute to your WebBrowser element.
Name: This WPF attribute will be automatically turned into a property in the C# code for the window. We use "MainBrowser".
Loaded. Please next add a Loaded attribute to your Window element. In the Window_Loaded method, we access the WebBrowser (with the name "MainBrowser") and call Navigate on it. We visit the Wikipedia website.
Based on: .NET 4.5 Example markup: XAML <Window x:Class="WpfApplication28.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded"> <Grid> <WebBrowser HorizontalAlignment="Left" Height="299" Margin="10,10,0,0" VerticalAlignment="Top" Width="497" Name="MainBrowser"/> </Grid> </Window> Example code: C# using System.Windows; namespace WpfApplication28 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { // ... Load this site. this.MainBrowser.Navigate("http://en.wikipedia.org/"); } } }
Example 2. The WebBrowser can access the network to download a web page. But it can also directly open a file on your local computer. This is done also with the Navigate method. We use the "file" scheme instead of "http".
Here: Please make sure to place the HTML file in a directory on your computer. Adjust the file URI to point to the file.
Example file: HTML <h1>Hi there!</h2> <p> file </p> Example code: C# using System.Windows; namespace WpfApplication28 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { // ... Load a local HTML page. this.MainBrowser.Navigate("file:///C:/folder/file"); } } }
GoBack, GoForward. The WebBrowser control allows navigation. We can go back or forward with the GoBack and GoForward methods. These are void methods. They will throw exceptions if no pages are available for navigation.
Tip: Please use the CanGoBack and CanGoForward properties before calling GoBack and GoForward. This will eliminate exceptions.
Summary. A WebBrowser control uses the Internet Explorer rendering engine to load a web page. We used this control to load a web page. We also used it to load an HTML file from the local disk.