About the
solution of embedding browser, "HTML5浏览器嵌入窗口程序解决方案" tell us how to choose and how to
use Embedding Chrominum Framwork ."支持HTML5内嵌浏览器解决方案--OpenWebKitSharp" tell us how to use
OpenWebKitSharp in WinForm(C#).But I feel unhappy because they are
from the net world,not my original works(by the way,I am very
grateful to them).Now let me tell you how to use OpenWebKitSharp in
WPF(C#).
在WPF工程中添加引用:JSCore.dll、OpenWebKitSharp.dll、WebKit.Interop.dll,它们是为了使用OpenWebKitSharp做准备的。
另外,再添加.Net的引用:System.Windows.Forms、WindowsFormsIntegration,它们是为了在WPF中使用WinForm控件所准备的。
测试的MainWindow.xaml.cs代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WebKit;
using WebKit.Interop;
namespace WpfApplication1
{
///
///
MainWindow.xaml 的交互逻辑
/// by
华仔103 [2014-03-30]
///
public
partial class MainWindow : Window
{
private WebKit.WebKitBrowser _browser = new
WebKit.WebKitBrowser();
System.Windows.Forms.Integration.WindowsFormsHost host =
new
System.Windows.Forms.Integration.WindowsFormsHost();
public MainWindow()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
this.Closing += new
System.ComponentModel.CancelEventHandler(MainWindow_Closing);
}
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
host.Width = 800;
host.Height = 300;
host.HorizontalAlignment = HorizontalAlignment.Left;
host.VerticalAlignment = VerticalAlignment.Bottom;
_browser.Width = (int)host.Width;
_browser.Height = (int)host.Height;
// Assign the ActiveX control as the host control's child.
host.Child = _browser;
// Add the interop host control to the Grid
// control's collection of child controls.
// 将host强制转化为UIElement是必要的,否则有些版本的VS编译器会报错
this.Grid1.Children.Add((UIElement)host);
}
void MainWindow_Closing(object sender,
System.ComponentModel.CancelEventArgs e)
{
_browser.Dispose();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
///
广告无处不在呀~
_browser.Navigate("http://blog.sina.com.cn/huazi103");
//_browser.GetScriptManager.CallFunction();//
应用程序调用JavaSCript的函数
//_browser.OpenDocument(@"C:\open-webkit-sharp\build\JSTest\page.html");
//_browser.Url = new
Uri(@"C:\open-webkit-sharp\build\JSTest\page.html");
}
}
}
PS:我曾试过直接在xaml文件中添加webKitSharp:WebKitBrowser控件,这样就不需要用代码实现WebKitBrowser控件的创建了,但可能是VS2010或之后版本的编译器将隐式转换更严格了,此种实现方法在某些机器编译时会报错。另外this.Grid1.Children.Add(host);也会报错,所以最后只能显式强制转换,写成了:this.Grid1.Children.Add((UIElement)host);也许这就是不能通过xaml文件实例化一个WebKitBrowser控件的原因。