Friday 14 June 2013

Create a WebBrowser in Wpf



In this article we will see how to create a web browser like internet explorer in wpf.
First drag the web browser control,  three buttons and one textbox from tool box.
Xaml Code

<Window x:Class="wpftheme.WebBrowser"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="WebBrowser" Height="600" Width="774" Initialized="Window_Initialized" WindowState="Maximized">
    <Grid>
        <Button Content="&lt;&lt;" Height="23" HorizontalAlignment="Left" Margin="0,12,0,0" Name="BackButton" Click="BackButton_Click" VerticalAlignment="Top" Width="40" />
        <Button Content="&gt;&gt;" Height="23" HorizontalAlignment="Left" Margin="40,12,0,0" Name="ForwardButton" Click="ForwardButton_Click" VerticalAlignment="Top" Width="38" />
        <TextBox Height="23" Text="Go to a Website" HorizontalAlignment="Left" Margin="84,13,0,0" Name="AddressTextBox" VerticalAlignment="Top" Width="559" KeyDown="AddressTextBox_KeyDown" FontStyle="Italic" />
        <Button Content="Go" Background="Green" Height="23" HorizontalAlignment="Left" Margin="649,13,0,0" Name="GoButton" Click="GoButton_Click" VerticalAlignment="Top" Width="36" />
        <WebBrowser  HorizontalAlignment="Left" Margin="12,44,0,0" Name="SampleWebBrowser"  VerticalAlignment="Top"  />
    </Grid>
</Window>


Here Backword Button click we can write predefined method GoBack().Also in forward button
GoForward() and in Go button set source for web browser.
Here is the C# Code:

   private void BackButton_Click(object sender, RoutedEventArgs e)
        {
            this.SampleWebBrowser.GoBack();
        }

        private void ForwardButton_Click(object sender, RoutedEventArgs e)
        {
            this.SampleWebBrowser.GoForward();
        }
        private void GoButton_Click(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrEmpty(this.AddressTextBox.Text.Trim()) && this.AddressTextBox.Text.Trim().CompareTo("Go to a Website") != 0)
            {
            this.SampleWebBrowser.Source = new Uri("http://" + this.AddressTextBox.Text.Trim());
            }
        }
        private void AddressTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Return)
            {
                this.SampleWebBrowser.Source = new Uri("http://" + this.AddressTextBox.Text.Trim());
            }
        }
        private void Window_Initialized(object sender, EventArgs e)
        {
            this.SampleWebBrowser.Source = new Uri("http://www.google.com");
        }


1 comment: