WPF 项目使用WebView2+的混合开发

一.背景

​ 公司开发一个网页项目需要和硬件进行通信,所以需要再开发一个桌面客户端,为了减少开发难度,考虑采用客户端嵌套网页的方案,最终实现采用wpf+webview2的混合开发的技术方案。

二. 参考资料

三. 使用案例

1. 安装webview2运行时

选择下载独立安装程序,下载完成后直接安装。
下载地址:<WebView2 - Microsoft Edge Developer>

2. 项目使用控件

  • 新建wpf应用程序,nuget安装Microsoft.Web.WebView2程序包
Install-Package Microsoft.Web.WebView2
  • 在主窗体添加命名空间
xmlns:wv2="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf"
  • 在主窗体添加webview控件
<Grid>
<wv2:WebView2 Name="webView" Source="http://192.168.2.161:8082/login" WebMessageReceived="webView_WebMessageReceived" />
</Grid>

3. 加载页面及页面交互

  • 在窗体加载事件中设置webview加载页面
//获取默认的路径
var url = SystemConfig.GetDefaultHtmlPath();
//如果加载配置成功,则设置为配置的路径
if (SystemConfig.LoadSystemConfig())
{
url = string.IsNullOrWhiteSpace(SystemConfig.Instance?.StartUrl) ? url : SystemConfig.Instance.StartUrl;
}
//修改webview页面地址
webView.Source = new Uri(url);
  • 客户端监听网页发送消息
//网页端代码
//盒子登记病人信息
function RegisterPatientInfo() {
var param = {
token: token,
applicationSubId: "4156794784846970880",
}
var args = {
command: 1,
json: JSON.stringify(param)
};
window.chrome.webview.postMessage(args);
}
//客户端代码
/// <summary>
/// WebView2消息处理回调函数
/// </summary>
private void webView_WebMessageReceived(object sender, CoreWebView2WebMessageReceivedEventArgs e)
{
var msgJson = e.WebMessageAsJson;
//回调函数耗时操作使用线程
Task.Factory.StartNew(() =>
{
//反序列化消息
var commandReq = JsonConvert.DeserializeObject<CommandReq>(msgJson);
if (commandReq == null) return;
//消息处理入口函数
var result = MainLogic(commandReq);
Application.Current.Dispatcher.BeginInvoke(() =>
{
//将处理的结果发消息给网页
webView.CoreWebView2.PostWebMessageAsJson(JsonConvert.SerializeObject(result));
});
});
}
  • 网页监听客户端发送消息
//网页端代码
window.onload = function () {
//监听客户端发送的消息
window.chrome.webview.addEventListener('message', args => {
//消息处理
alert("状态:" + args.data.Code + " 消息:" + args.data.Message);
});
}

​ 客户端代码 同上段客户端代码

posted @ 2023-04-24 10:17  热烈的少年  阅读(208)  评论(0)    收藏  举报