我在我的WPF应用程序中使用WebBrowser-Control,如下:
<WebBrowser x:Name="webBrowser" Margin="0,28,0,0" />
现在,当我导航到一个包含链接的mht页面并且用户单击其中一个链接时,新页面将在WebBrowser-Control中打开。但是它应该在一个新的默认浏览器窗口中打开。WebBrowser-Control中的内容不应更改。 有没有一种方法可以改变这种行为?
我在我的WPF应用程序中使用WebBrowser-Control,如下:
<WebBrowser x:Name="webBrowser" Margin="0,28,0,0" />
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
:这是一个引用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>
我认为WebBrowser
并不是打算像这样,因为即使在普通浏览器中,如果单击超链接并且它代表直接的URL(而不是基于JavaScript的超链接),它也会在该浏览器窗口(和该特定选项卡)中打开URL。WebBrowser
控件模拟了浏览器本身的这种基本行为。
我认为你可以右键单击超链接,然后选择“在新窗口中打开”(查看该选项是否在WebBrowser
控件中启用)。
如果该选项被禁用,则可以使用特殊的HTMLHost API来启用它。
默认情况下,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];
}
GetDefaultBrowserPath
代码。使用 Process.Start(url)
(即不带 GetDefaultBrowserPath()
参数)更好,因为它会请求操作系统打开网页,而操作系统会自然地使用默认浏览器。这样你就不需要注册表代码,避免了破坏向前兼容性的风险。 - HughHughTeotl