Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebBrowser-Control - open default browser on click on link

I use the WebBrowser-Control in my WPF-Application like

    <WebBrowser x:Name="webBrowser" Margin="0,28,0,0" />

Now, when I navigate to a mht-page which contains links and the user click on one of this link, the new page is opened in the WebBrowser-Control. But it should be opened in a new Default-Browser-Window. The content in the WebBrowser-Control should not be changed. Is there a way to change this behavior?

like image 232
BennoDual Avatar asked Jun 07 '12 07:06

BennoDual


1 Answers

You can open the new page in default browser using Proces.Start() on Navigating event and set e.Cancel = true; so that the page in the control will not change.

Example:

@MainWindow.xaml.cs

using System.Diagnostics;
using System.Windows;
using System.Windows.Navigation;

namespace OpenDefaultBrowser
{
    public partial class MainWindow : Window
    {
        private static bool willNavigate;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void webBrowser1_Navigating(object sender, NavigatingCancelEventArgs e)
        {
            // first page needs to be loaded in webBrowser control
            if (!willNavigate)
            {
                willNavigate = true;
                return;
            }

            // cancel navigation to the clicked link in the webBrowser control
            e.Cancel = true;

            var startInfo = new ProcessStartInfo
            {
                FileName = e.Uri.ToString()
            };

            Process.Start(startInfo);
        }
    }
}

@MainWindow.xaml

<Window x:Class="OpenDefaultBrowser.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="464" Width="1046">
    <Grid>
        <WebBrowser Height="425" HorizontalAlignment="Left" Name="webBrowser1" VerticalAlignment="Top" Width="1024" Source="http://stackoverflow.com/" Navigating="webBrowser1_Navigating" />
    </Grid>
</Window>
like image 58
Răzvan Flavius Panda Avatar answered Sep 28 '22 05:09

Răzvan Flavius Panda