Blue Theme Orange Theme Green Theme Red Theme
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Discover the top 5 tips for understanding .NET Interop
Search :       Advanced Search »
Home » WPF » Web Browser control in WPF

Web Browser control in WPF

In this article, I am going to show you; how to work with Web Browser control in WPF? We will be opening a web site (even a Silverlight Enabled web site in WPF application) in the new Web Browser control.

Author Rank :
Page Views : 42159
Downloads : 768
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
webbrowsercontrol.zip
 
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 



Objective:

In this article, I am going to show you; how to work with Web Browser control in WPF? We will be opening a web site (even a Silverlight Enabled web site in WPF application) in the new Web Browser control.

Expected Output


1.gif

Web Browser Control

This control is added in .Net 3.5 SP1. This is used to browse the websites in a WPF application. This control could be used to execute scripts also. This control is capable of loading Silverlight enabled site also. This feature makes it a great control.

2.gif

Working Explanation:

I do have two buttons on the form. One button will load the requested site from the user text box. And another is used to load the default web site for this window application. I have taken Google as default website. There is one text box also. In this text box user could enter the site she is willing to load in the browser.

Step 1: Create a WPF Application.

Open the Visual Studio 2008 and create a new WPF Application.

3.gif

Step 2: Design the window


Open the WPF application in blend and design the window.

4.gif

  1. I have divided the default grid in three rows and two columns
  2. In first row , I put one TextBlock and one TextBox
  3. In TextBox user will input site address she wants to load in the web browser.
  4. In second row, I put one border layout. And merged the columns.
  5. Then I put one WebBrowser control in the second row of Grid inside border Layout.
  6. In third row, I put one StackPanel with horizontal orientation.
  7. Then I put two buttons in the third row. One button is to load the default website and another to load the requested website.

Windows1.Xaml (For your reference)

<
Window x:Class="webbrowsercontrol.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="400" Width="400">

   
<Grid>
         
<Grid.Background>
                  
<LinearGradientBrush MappingMode="RelativeToBoundingBox" EndPoint="0.5,1" StartPoint="0.5,0">
                            
<GradientStop Color="#FF000000" Offset="0"/>
                            
<GradientStop Color="#FF52698D" Offset="1"/>
                  
</LinearGradientBrush>
         
</Grid.Background>
         
<Grid.ColumnDefinitions>
                  
<ColumnDefinition Width="0.226*"/>
                  
<ColumnDefinition Width="0.774*"/>
         
</Grid.ColumnDefinitions>
         
<Grid.RowDefinitions>
                  
<RowDefinition Height="0.091*"/>
                  
<RowDefinition Height="0.755*"/>
                  
<RowDefinition Height="0.154*"/>
         
</Grid.RowDefinitions>
         
<TextBlock Margin="1,1,1,1" Text="Navigate To" TextWrapping="Wrap" Foreground="#FFF4EAEA"/>
         
<TextBox x:Name="txtLoad" Margin="0,1,0,1" Grid.Column="1" Text="" TextWrapping="Wrap" Background="#FFBDA4A4" HorizontalAlignment="Stretch" Cursor="No" Foreground="#FFE91D1D" Width="Auto" Height="30" VerticalAlignment="Top"/>
         
<Border Margin="1,1,1,1" Grid.ColumnSpan="2" Grid.Row="1" BorderBrush="#FF000000" BorderThickness="1,1,1,1">
                  
<WebBrowser x:Name="myBrowser" Margin="0,0,0,0" Cursor="Arrow"/>
         
</Border>
         
<Border Margin="1,0,1,0" Grid.ColumnSpan="2" Grid.Row="2" BorderBrush="#FF000000" BorderThickness="1,1,1,1">
                  
<StackPanel Margin="0,0,0,0" Orientation="Horizontal">
                            
<Button x:Name="btnExternal" Margin="0,0,0,0" Width="175" Content="Load   Requested Site" FontWeight="Bold" FontSize="14" Click="btnExternal_Click">                                      <Button.Background>
                                               
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                                                         
<GradientStop Color="#FF000000" Offset="0"/>
                                                         
<GradientStop Color="#FFFFFFFF" Offset="1"/>
                                                         
<GradientStop Color="#FFC44848" Offset="0.289"/>
                                               
</LinearGradientBrush>
                                     
</Button.Background>
                            
</Button>
                            
<Button x:Name="btnInternal" Margin="9,0,0,0" Width="175" Content="Load Default Site" Foreground="#FF0F0D0D" FontWeight="Bold" FontSize="14" Click="btnInternal_Click">
                                     
<Button.Background>
                                               
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                                                         
<GradientStop Color="#FF000000" Offset="0"/>
                                                         
<GradientStop Color="#FFFFFFFF" Offset="1"/>
                                                         
<GradientStop Color="#FFA93030" Offset="0.211"/>
                                               
</LinearGradientBrush>
                                     
</Button.Background>
                            
</Button>
                  
</StackPanel>
         
</Border>
  
</Grid>
</
Window>

Step 3: Navigating the Sites in WebBrowser control

I have given Name of WebBrowser control is myBrowser. If you see XAML code closely, you would find that.

Navigate method on WebBrowser control is used to load the site in the control.

So, if you want to load Google in WebBrowser control, you need to call Navigate method like below,

myBrowser.Navigate(new Uri(http://www.google.com));

Navigate Method


5.gif

Navigate method is overloaded with two arguments. One takes only URI address to be load and other takes URI source as well as Frame name along with other parameters.

Load Default Site Button


I have made c-sharpcorner.com as default web site to be loaded. So when user will click on Load Default site button, this site will get loaded in the Browser control.

private
void btnInternal_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            myBrowser.Navigate(new Uri("http://www.c-sharpcorner.com"));         

        }

Load Requested Site Button

When user will give any site address in textbox that site will get loaded on click event of this button.

private
void btnExternal_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            Uri ui = new Uri(txtLoad.Text.Trim(), UriKind.RelativeOrAbsolute);
            myBrowser.Navigate(ui);

        }

Windows.Xaml.cs

using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
using
System.Windows;
using
System.Windows.Controls;
using
System.Windows.Data;
using
System.Windows.Documents;
using
System.Windows.Input;
using
System.Windows.Media;
using
System.Windows.Media.Imaging;
using
System.Windows.Navigation;
using
System.Windows.Shapes; 

namespace webbrowsercontrol
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
            myBrowser.Navigate(new Uri("http://www.google.com"));
        } 

        private void btnExternal_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            Uri ui = new Uri(txtLoad.Text.Trim(), UriKind.RelativeOrAbsolute);
            myBrowser.Navigate(ui);
        } 

        private void btnInternal_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            myBrowser.Navigate(new Uri("http://www.c-sharpcorner.com"));
        }
    }
}

Step 4: Run the application

Press F5 to run the application. If you see while loading Google.com is loaded in Browser Control. Because if you see closely Windows1() constructor , I am loading the browser control with google over there.

6.gif

Click on Load Default site button, it will load c-sharpcorner.

Type some site address in textbox at right top corner and click Load requested site.

7.gif

Able to Load Silverlight enabled site

Most interesting Part is type http://silverlight.net/ in the textbox and click on Load Requested site. It would load SilverLight site. It means WebBrowser control is capable of loading a Silverlight enabled site also.

8.gif

Conclusion:

We saw, how to work with BrowserControl in WPF. Please download the attached code for better reference.

Happy Coding.
 

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Dhananjay Kumar
Dhananjay Kumar is a developer who blogs at http://debugmode.net/. He is Microsoft MVP ,Telerik MVP and Mindcracker MVP. You can follow him on twitter  @debug_mode
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Comments
WPF Browser and Proxy Settings by Joe On February 2, 2010
I was wondering if anyone had be able to authenticate against a proxy without requiring the user to log in.
Reply | Email | Modify 
Re: WPF Browser and Proxy Settings by Dhananjay On February 5, 2010
right now I have no idea .. I will do explore and post an article :)
Reply | Email | Modify 
Re: Re: WPF Browser and Proxy Settings by Leon On February 17, 2010

I'm looking for a way to play video, specifically, movies from youtube.com, in a WPF application.

See what happens when you load http://www.youtube.com/ into Navigate To field in your application.

Any clue?

Thanks!

Reply | Email | Modify 
One doubt by rekha On September 14, 2010
In .Net 3.5 ,there is no web browser control.Then  how u added WebBrowser control in the second row of Grid inside border Layout.Is there any dll for to add reference?
Reply | Email | Modify 
Getting this following error by rekha On September 14, 2010
Error 2 The tag 'WebBrowser' does not exist in XML namespace 'http://schemas.microsoft.com/winfx/2006/xaml/presentation'. Line 24 Position 8. C:\Documents and Settings\eyet\My Documents\Downloads\webbrowsercontrol\webbrowsercontrol\Window1.xaml 24 8 webbrowsercontrol

Reply | Email | Modify 
ArgumentException by Anindita On November 25, 2010
It throws an ArgumentException (No relative Uri's allowed" on btnExternal_Click() mehtod @mybrowser .Navigate(ui);) when trying to load www.silverlight.net on clicking "Load Requested Site" button.
Reply | Email | Modify 
Using you code sample by iuoiuoi On June 8, 2011
I am not able to load any flash, silverlight or other, enabled site. Any idea as to why this is happening? I am using Win 7. Thanks
Reply | Email | Modify 
Team Foundation Server Hosting
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.