c# - WebBrowser-Control - 点击链接打开默认浏览器

标签 c# .net wpf webbrowser-control

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

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

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

最佳答案

您可以使用 Proces.Start() 在默认浏览器中打开新页面在 Navigating 事件上设置 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>

关于c# - WebBrowser-Control - 点击链接打开默认浏览器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10927696/

相关文章:

c# - 在每个不同的线程上调用服务并等待所有服务响应

WPF嵌套项目控件EventToCommand绑定(bind)路径错误

c# - 重复2种方法变成1种方法

c# - 如何构建自定义 AngleSharp 元素并将 HTML 部分插入/转换到元素中

c# - 哈希表到字典的转换

c# - 在 Windows 10 和 7 上部署 WPF c#

c# - 无法绑定(bind)到 ReactiveUI 中覆盖的 WPF TextBox

c# - 搜索YouTube视频并找到第一个结果的链接的最简单方法是什么?

c# - ServiceStack.Interfaces 中系统版本=4.0.0.0 与系统版本=2.0.5.0 之间的冲突

asp.net - IIdentity、IPrincipal、OWIN、IdentityUser 和 IUser<string> 如何组合在一起?