下面是這將打開在WPF WebBrowser
的另一個實例的所有導航鏈接(包括新窗口中的鏈接)的樣本WPF應用程序。它使用底層的WebBrowser
ActiveX控件到達那裏並取決於SHDocVw.dll COM互操作程序集。首先生成SHDocVw.dll:tlbimp.exe ieframe.dll
,然後添加爲項目的引用。請注意0用於區分用戶導航和程序導航(通過webBrowser.Navigate
)。
C#:
using System;
using System.Windows;
using System.Windows.Controls;
using System.Reflection;
namespace WpfWebBrowser
{
// http://stackoverflow.com/q/19170109/1768303
public partial class MainWindow : Window
{
static object GetActiveXInstance(WebBrowser wb) {
// get the underlying WebBrowser ActiveX object;
// this code depends on SHDocVw.dll COM interop assembly,
// generate SHDocVw.dll: "tlbimp.exe ieframe.dll",
// and add as a reference to the project
return wb.GetType().InvokeMember("ActiveXInstance",
BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.NonPublic,
null, wb, new object[] { }) as SHDocVw.WebBrowser;
}
public MainWindow()
{
InitializeComponent();
this.Loaded += (s, e) =>
{
var axWbMainV1 = (SHDocVw.WebBrowser_V1)GetActiveXInstance(this.wbMaster);
var axWbSlaveV1 = (SHDocVw.WebBrowser_V1)GetActiveXInstance(this.wbSlave);
var manualNavigation = false;
// Use WebBrowser_V1 events as BeforeNavigate2 doesn't work with WPF WebBrowser
axWbMainV1.BeforeNavigate += (string URL, int Flags, string TargetFrameName, ref object PostData, string Headers, ref bool Cancel) =>
{
if (!manualNavigation)
return;
Cancel = true;
axWbMainV1.Stop();
axWbSlaveV1.Navigate(URL, Flags, TargetFrameName, PostData, Headers);
};
axWbMainV1.FrameBeforeNavigate += (string URL, int Flags, string TargetFrameName, ref object PostData, string Headers, ref bool Cancel) =>
{
if (!manualNavigation)
return;
Cancel = true;
axWbMainV1.Stop();
axWbSlaveV1.Navigate(URL, Flags, TargetFrameName, PostData, Headers);
};
axWbMainV1.NavigateComplete += (string URL) =>
{
manualNavigation = true;
};
axWbMainV1.FrameNavigateComplete += (string URL) =>
{
manualNavigation = true;
};
axWbMainV1.NewWindow += (string URL, int Flags, string TargetFrameName, ref object PostData, string Headers, ref bool Processed) =>
{
if (!manualNavigation)
return;
Processed = true;
axWbMainV1.Stop();
axWbSlaveV1.Navigate(URL, Flags, String.Empty, PostData, Headers);
};
manualNavigation = false;
axWbMainV1.Navigate("http://www.w3.org/");
};
}
}
}
XAML:
<Window x:Class="WpfWebBrowser.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Width="800" Height="600">
<StackPanel>
<WebBrowser Margin="4" Name="wbMaster" Height="300"/>
<WebBrowser Margin="4" Name="wbSlave" Height="300"/>
</StackPanel>
</Window>
爲什麼難道你不創建一個HTML頁面框架集TAG,包含兩個框架,一個幀包含簡單的HTML網頁刮板,其他框架成爲目標。然後在WebBrowser中加載包含此Frameset的HTML。 – Tony
請參閱http://msdn.microsoft.com/zh-CN/library/system.windows.forms.webbrowser.objectforscripting.aspx – Yaur