日常开发中,我们需要将一些Web页面嵌入到桌面客户端软件中。下面我们使用CefSharp嵌入浏览器来实现。

首先先介绍一下CefSharp嵌入式浏览器,它是基于Google浏览器的一个组件,我们可以在WPF/WinForm客户端软件中使用它。CefSharp的代码托管在GitHub上,.NET (WPF and Windows Forms) bindings for the Chromium Embedded Framework

目前最新版本的CefSharp是41.0版本,如果你的客户端软件需要支持WIN XP操作系统,建议使用CefSharp.Wpf 1.25.7及之前的版本。可以从Nuget上获取到具体的内容。在新版本的CefSharp中,已经取消了对WIN XP系统的支持。

具体的实现:(首先引用CefSharp.dll,CefSharp.Wpf.dll 另外将icudt.dll,libcef.dll这两个Dll放置在bin/Debug或者bin/Release目录下)

先创建一个UserControl,并继承IRequestHandler接口,代码如下:

UI:

<UserControl x:Class="EmbeddedWebBrowserSolution.WebPageViewer"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:EmbeddedWebBrowserSolution"
xmlns:uc="clr-namespace:EmbeddedWebBrowserSolution"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid x:Name="MainGrid">
<uc:MaskLoading x:Name="maskLoading"/>
</Grid>
</UserControl>

Code:

public partial class WebPageViewer : UserControl, IRequestHandler
{
private WebView _view; public WebPageViewer(string url)
{
InitializeComponent(); CEF.Initialize(new Settings { LogSeverity = LogSeverity.Disable, PackLoadingDisabled = true }); BrowserSettings browserSetting = new BrowserSettings { ApplicationCacheDisabled = true, PageCacheDisabled = true }; _view = new WebView(string.Empty, browserSetting)
{
Address = url,
RequestHandler = this,
Background = Brushes.White
}; _view.LoadCompleted += _view_LoadCompleted; MainGrid.Children.Insert(, _view);
} private void _view_LoadCompleted(object sender, LoadCompletedEventArgs url)
{
Dispatcher.BeginInvoke(new Action(() =>
{
maskLoading.Visibility = Visibility.Collapsed;
}));
} public void View(string url)
{
if(_view.IsBrowserInitialized)
{
_view.Visibility = Visibility.Hidden; maskLoading.Visibility = Visibility.Visible; _view.Load(url);
}
} #region IRequestHandler
public bool GetAuthCredentials(IWebBrowser browser, bool isProxy, string host, int port, string realm, string scheme, ref string username, ref string password)
{
return false;
} public bool GetDownloadHandler(IWebBrowser browser, string mimeType, string fileName, long contentLength, ref IDownloadHandler handler)
{
return true;
} public bool OnBeforeBrowse(IWebBrowser browser, IRequest request, NavigationType naigationvType, bool isRedirect)
{
return false;
} public bool OnBeforeResourceLoad(IWebBrowser browser, IRequestResponse requestResponse)
{
return false;
} public void OnResourceResponse(IWebBrowser browser, string url, int status, string statusText, string mimeType, WebHeaderCollection headers)
{ }
#endregion
}

下一步,在MainWindow上来承载,

UI:

    <Grid>
<DockPanel>
<StackPanel DockPanel.Dock="Top" Orientation="Horizontal">
<TextBlock Text="Address:" Margin="5"/>
<TextBox x:Name="txtAddress" Width="350" Margin="5"/>
<Button Content="Go" Margin="5" Click="OnGoClick" IsDefault="True"/>
</StackPanel> <Grid x:Name="MainGrid"> </Grid>
</DockPanel>
</Grid>

Code:

        private void OnGoClick(object sender, RoutedEventArgs e)
{
string url = txtAddress.Text; if (!string.IsNullOrWhiteSpace(url))
{
WebPageViewer viewer = new WebPageViewer(url);
MainGrid.Children.Insert(,viewer);
}
}

注意,需要将工程Platform Target设置为X86。

运行效果:

到这里,一个使用CefSharp来承载Web页面的例子就算完成了。

相比于WPF内置的WebBrowser,CefSharp在处理JS回掉时,比WebBrowser方便很多。请看下面的例子:

我们有这样一个HTML页面:

<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script type="text/javascript">
function callback()
{
callbackObj.showMessage('message from js');
}
</script>
</head>
<body>
<input type="button" value="Click" onclick="callback()" ID="Button">
</body>
</html>

增加一个类,叫做:CallbackObjectForJs

    public class CallbackObjectForJs
{
public void showMessage(string msg)
{
MessageBox.Show(msg);
}
}

 注意这个方法的名称必须小写。

改造一下WebPageViewer类,在构造后WebView之后,注册一个JS对象,

        //...
public WebPageViewer(string url)
{
InitializeComponent(); CEF.Initialize(new Settings { LogSeverity = LogSeverity.Disable, PackLoadingDisabled = true }); BrowserSettings browserSetting = new BrowserSettings { ApplicationCacheDisabled = true, PageCacheDisabled = true }; _view = new WebView(string.Empty, browserSetting)
{
Address = url,
RequestHandler = this,
Background = Brushes.White
}; _view.RegisterJsObject("callbackObj", new CallbackObjectForJs()); _view.LoadCompleted += _view_LoadCompleted; MainGrid.Children.Insert(, _view);
}
//...

运行效果如下:

通过这样的方式,我们可以很好的实现Web页面与客户端程序之间的交互。点击这里下载代码。

感谢您的阅读!

在WPF中使用CefSharp嵌入浏览器的更多相关文章

  1. 在WPF中使用CefSharp嵌入浏览器(转)

    在WPF中使用CefSharp嵌入浏览器   日常开发中,我们需要将一些Web页面嵌入到桌面客户端软件中.下面我们使用CefSharp嵌入浏览器来实现. 首先先介绍一下CefSharp嵌入式浏览器,它 ...

  2. WPF中使用cefsharp

    原文:WPF中使用cefsharp 新入职一家公司,由写服务端接口变成了软硬件通信.服务器.客户端.C/S.B/S乱七八糟各种打杂.首先接收一个WPF项目,因为不熟WPF,再加上前端我也不熟,我打算使 ...

  3. 【WPF】使用CefSharp嵌入HTML网页

    需求:WPF项目中要做用户的商铺主页,由于考虑到每个商家的主页布局各不相同,不能用XAML写死布局.最好的办法是WPF这边XAML写好一个容器,用户使用HTML可视化编辑器(比如这个)来准备好网页,输 ...

  4. .net core Wpf中使用cefsharp加载本地html网页,并且cefsharp支持any cpu

    第一步,在程序包管理器安装 cefsharp.wpf 第二步 您必须在项目的第一个 < propertygroup > 中添加 < cefsharpanycpusupport > ...

  5. wpf中使用cefsharp加载本地html网页并实现cs和js的交互,并且cefsharp支持any cpu

    废话少说,直接上代码: 第一步: 第二步: 第三步: 第四步: App.xaml.cs对应的代码: using CefSharp; using CefSharp.Wpf; using System; ...

  6. 浏览器扩展系列————在WPF中定制WebBrowser快捷菜单

    原文:浏览器扩展系列----在WPF中定制WebBrowser快捷菜单 关于如何定制菜单可以参考codeproject上的这篇文章:http://www.codeproject.com/KB/book ...

  7. 在WPF中嵌入WebBrowser可视化页面

    无论是哪种C/S技术,涉及数据可视化就非常的累赘了,当然大神也一定有,只不过面向大多数人,还是通过网页来实现,有的时候不想把这两个功能分开,一般会是客户的原因,所以我们打算在WPF中嵌入WebBrow ...

  8. WPF中嵌入普通Win32程序的方法

    公司现在在研发基于.Net中WPF技术的产品,由于要兼容旧有产品,比如一些旧有的Win32程序.第三方的Win32程序等等,还要实现自动登录这些外部Win32程序,因此必须能够将这些程序整合到我们的系 ...

  9. WPF中嵌入Office编辑器(支持Word、Excel、PPT、Visio等)

    现在有一个项目,需要使用wpf做一个简单的客户端,用来生成word.excel.ppt.visio等文档,这就需要能够在wpf中嵌入office的编辑器,并对office文档进行编辑. 在网上搜索了一 ...

随机推荐

  1. phpcms模块开发简易教程

    简介: 在phpcms中,各个功能是以模块为单位定义的(对应modules目录),如果需要新增功能最好的办法就是开发一个模块,然后复制到phpcms目录下,然后进入后台安装即可. 官方说明: phpc ...

  2. phpcms新闻详情页上一篇下一篇的实现

    在新闻详情页(show.html或show_*.html) 只需要添加类似如下代码即可: <div>上一篇:<a href="{$previous_page[url]}&q ...

  3. 2017/1/7 学习笔记 jar包,maven

    ① 关于tar,jar,war文件 tar是通用的另一种打包格式,为了部署到服务器时方便. jar是java app server识别的java部署格式,其实是Zip文件,只是内部的文件有规范. wa ...

  4. C#的contextMenuStrip右键没反应的可能原因

    contextMenuStrip设置右键菜单,但是新手常常忽略一个问题,我要遇到了,即没有设置contextMenuStrip所在控件的contextMenuStrip属性,需要把contextMen ...

  5. CentOS用yum安装、配置MariaDB

    .创建/etc/yum.repos.d/MariaDB.repo文件,这里用到了刚刚发布正式版的10. [mariadb] name = MariaDB baseurl = http://yum.ma ...

  6. 【leetcode】Partition List

    Partition List Given a linked list and a value x, partition it such that all nodes less than x come ...

  7. 【leetcode】Merge Intervals

    Merge Intervals Given a collection of intervals, merge all overlapping intervals. For example,Given  ...

  8. python之errno

    http://www.cnblogs.com/Security-Darren/p/4168392.html errno.EWOULDBLOCK 操作将会阻塞

  9. Java for LeetCode 230 Kth Smallest Element in a BST

    解题思路: 直接修改中序遍历函数即可,JAVA实现如下: int res = 0; int k = 0; public int kthSmallest(TreeNode root, int k) { ...

  10. Filezilla无法确定拖放操作目标,由于shell未正确安装__解决办法

    开始--运行--输入regsvr32空格   然后将filezila安装目录下的fzshellext.dll拖拽到[regsvr32空格]之后 注:64位电脑注意拖拽的文件为fzshellext_64 ...