5

我在我的 WPF 应用程序中使用 WebBrowser-Control,例如

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

现在,当我导航到包含链接的 mht 页面并且用户单击此链接之一时,新页面将在 WebBrowser-Control 中打开。但它应该在新的默认浏览器窗口中打开。不应更改 WebBrowser-Control 中的内容。有没有办法改变这种行为?

4

3 回答 3

15

您可以在导航事件中使用Proces.Start()在默认浏览器中打开新页面,并设置e.Cancel = true;为控件中的页面不会更改。

例子:

@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>
于 2012-06-07T12:01:08.650 回答
0

我认为WebBrowser即使在普通浏览器中,如果单击超链接并且它表示一个简单的 URL(而不是基于 javascript 的超链接),它也不会像这样,它将在该浏览器窗口(和该特定选项卡)本身中打开 URL . WebBrowser控件模仿浏览器本身的这种基本行为。

我认为您可以右键单击超链接并说“在新窗口中打开”(查看该选项是否在WebBrowser控件中启用)。

如果该选项被禁用,您可以使用特殊的 HTMLHost API 来启用它。

于 2012-06-07T08:30:19.533 回答
-1

默认情况下,Web 浏览器控件在单击链接时不会打开默认浏览器,它仅在 Internet Explorer 中打开在浏览器内单击的链接。现在我们可以使用 _DocumentCompleted 事件,但它需要一个基于事件的触发器,比如链接按钮,才能工作。现在的问题是,如果浏览器控件中的 html 有 href,那么这甚至不起作用。解决方案是使用 _NewWindow 事件。代码如下

/* The event handler*/
private void webBrowser1_NewWindow(object sender, CancelEventArgs e)
        {
            var webbrowser = (WebBrowser)sender;
            e.Cancel = true;
            OpenWebsite(webbrowser.StatusText.ToString());
            webbrowser = null;
        }

/* The function call*/
public static void OpenWebsite(string url)
        {
            Process.Start(GetDefaultBrowserPath(), url);
        }

 private static string GetDefaultBrowserPath()
        {
            string key = @"http\shell\open\command";
            RegistryKey registryKey =
            Registry.ClassesRoot.OpenSubKey(key, false);
            return ((string)registryKey.GetValue(null, null)).Split('"')[1];
        }

欢迎提出改进建议。快乐编码。

于 2012-08-22T08:16:29.023 回答