当前位置: 首页 > news >正文

windows vs2022 MFC使用webview2嵌入网页

Microsoft Edge WebView2 控件允许在本机应用中嵌入 web 技术(HTML、CSS 以及 JavaScript)。 WebView2 控件使用 Microsoft Edge 作为绘制引擎,以在本机应用中显示 web 内容。

一、通过菜单“项目”-“管理NuGet程序包”,下载相关包

二、安装 Microsoft.Web.WebView2

       在“浏览”分页的左上角的搜索栏中,键入 Microsoft.Web.WebView2,选择对应的版本,然后点击按钮安装

三、安装Microsoft.Windows.ImplementationLibrary

在“浏览”分页的左上角的搜索栏中,键入 Microsoft.Windows.ImplementationLibrary,选择对应的版本,然后点击按钮安装

四、添加界面消息映射

在对话框界面右击,选择“类向导”

 添加WM_CREATE和WM_SIZE消息:

五、添加代码

在MFCApplication1Dlg.h头文件中添加:

#include <iostream>
#include <wrl.h>
#include <wil/com.h>
#include "WebView2.h"#include <string>
#include <vector>
using namespace std;
using namespace Microsoft::WRL;// Pointer to WebViewController
static wil::com_ptr<ICoreWebView2Controller> webviewController = nullptr;// Pointer to WebView window
static wil::com_ptr<ICoreWebView2> webview = nullptr;

 在构造函数中添加:

CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);

在析构函数中添加:

CoUninitialize();

在OnSize函数中添加:

if (webviewController != nullptr) {RECT bounds;GetClientRect(&bounds);webviewController->put_Bounds(bounds);
};

在OnCreate函数中添加:

HWND hWnd = this->m_hWnd;// TODO:  在此添加您专用的创建代码// <-- WebView2 sample code starts here -->// Step 3 - Create a single WebView within the parent window// Locate the browser and set up the environment for WebViewCreateCoreWebView2EnvironmentWithOptions(nullptr, nullptr, nullptr,Callback<ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler>([hWnd](HRESULT result, ICoreWebView2Environment* env) -> HRESULT {// Create a CoreWebView2Controller and get the associated CoreWebView2 whose parent is the main window hWndenv->CreateCoreWebView2Controller(hWnd, Callback<ICoreWebView2CreateCoreWebView2ControllerCompletedHandler>([hWnd](HRESULT result, ICoreWebView2Controller* controller) -> HRESULT {if (controller != nullptr) {webviewController = controller;webviewController->get_CoreWebView2(&webview);}// Add a few settings for the webview// The demo step is redundant since the values are the default settingswil::com_ptr<ICoreWebView2Settings> settings;webview->get_Settings(&settings);settings->put_IsScriptEnabled(TRUE);settings->put_AreDefaultScriptDialogsEnabled(TRUE);settings->put_IsWebMessageEnabled(TRUE);// Resize WebView to fit the bounds of the parent windowRECT bounds;::GetClientRect(hWnd, &bounds);webviewController->put_Bounds(bounds);// Schedule an async task to navigate to Bingwebview->Navigate(L"https://www.bing.com/");// <NavigationEvents>// Step 4 - Navigation events// register an ICoreWebView2NavigationStartingEventHandler to cancel any non-https navigationEventRegistrationToken token;webview->add_NavigationStarting(Callback<ICoreWebView2NavigationStartingEventHandler>([](ICoreWebView2* webview, ICoreWebView2NavigationStartingEventArgs* args) -> HRESULT {wil::unique_cotaskmem_string uri;args->get_Uri(&uri);std::wstring source(uri.get());if (source.substr(0, 5) != L"https") {args->put_Cancel(true);}return S_OK;}).Get(), &token);// </NavigationEvents>// <Scripting>// Step 5 - Scripting// Schedule an async task to add initialization script that freezes the Object objectwebview->AddScriptToExecuteOnDocumentCreated(L"Object.freeze(Object);", nullptr);// Schedule an async task to get the document URLwebview->ExecuteScript(L"window.document.URL;", Callback<ICoreWebView2ExecuteScriptCompletedHandler>([](HRESULT errorCode, LPCWSTR resultObjectAsJson) -> HRESULT {LPCWSTR URL = resultObjectAsJson;//doSomethingWithURL(URL);return S_OK;}).Get());// </Scripting>// <CommunicationHostWeb>// Step 6 - Communication between host and web content// Set an event handler for the host to return received message back to the web contentwebview->add_WebMessageReceived(Callback<ICoreWebView2WebMessageReceivedEventHandler>([](ICoreWebView2* webview, ICoreWebView2WebMessageReceivedEventArgs* args) -> HRESULT {wil::unique_cotaskmem_string message;args->TryGetWebMessageAsString(&message);// processMessage(&message);webview->PostWebMessageAsString(message.get());return S_OK;}).Get(), &token);// Schedule an async task to add initialization script that// 1) Add an listener to print message from the host// 2) Post document URL to the hostwebview->AddScriptToExecuteOnDocumentCreated(L"window.chrome.webview.addEventListener(\'message\', event => alert(event.data));" \L"window.chrome.webview.postMessage(window.document.URL);",nullptr);// </CommunicationHostWeb>return S_OK;}).Get());return S_OK;}).Get());

六、截图

头文件:

构造函数和析构函数:

OnSize函数:

 

OnCreate函数:

运行截图:

 参考文档:https://blog.51cto.com/fish/6178983

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • 大数据-96 Spark 集群 SparkSQL Scala编写SQL操作SparkSQL的数据源:JSON、CSV、JDBC、Hive
  • [ComfyUI]Flux+MiniCPM-V强强联手艺术创意,媲美GPT4V级国产多模态视觉大模型
  • 【C/C++】pointer vs reference
  • JavaScript - Ajax
  • Spring常用的注解有哪些?作用是什么?怎么用?
  • Python 爬虫入门(十二):正则表达式「详细介绍」
  • outlook在“对我发送的邮件应用规则”时只能移动邮件副本的问题和解决方案
  • 缔造“神话”的不止悟空,海信电视也有“画质神话”
  • 【2024年】为Python股票量化分析最新整理的免费股票数据API接口之实时数据
  • ROS机器人专用云台相机防抖摄像头
  • 2024Go语言面试宝典Golang零基础实战项目面试八股力扣算法笔记等
  • 【jvm】jvm方法和栈帧的关系
  • 【后端学前端】纯HTML实现响应式布局
  • 03-JavaScript高阶( 代码)
  • C语言—指针(2)
  • #Java异常处理
  • 【知识碎片】第三方登录弹窗效果
  • 2019.2.20 c++ 知识梳理
  • Docker 1.12实践:Docker Service、Stack与分布式应用捆绑包
  • HTML5新特性总结
  • Java 多线程编程之:notify 和 wait 用法
  • Quartz初级教程
  • Terraform入门 - 3. 变更基础设施
  • Vue组件定义
  • 前端面试题总结
  • 云栖大讲堂Java基础入门(三)- 阿里巴巴Java开发手册介绍
  • 掌握面试——弹出框的实现(一道题中包含布局/js设计模式)
  • hi-nginx-1.3.4编译安装
  • scrapy中间件源码分析及常用中间件大全
  • Unity3D - 异步加载游戏场景与异步加载游戏资源进度条 ...
  • ​必胜客礼品卡回收多少钱,回收平台哪家好
  • ​马来语翻译中文去哪比较好?
  • #pragma pack(1)
  • #systemverilog# 之 event region 和 timeslot 仿真调度(十)高层次视角看仿真调度事件的发生
  • #微信小程序(布局、渲染层基础知识)
  • (160)时序收敛--->(10)时序收敛十
  • (4)STL算法之比较
  • (C语言)输入自定义个数的整数,打印出最大值和最小值
  • (超详细)语音信号处理之特征提取
  • (初研) Sentence-embedding fine-tune notebook
  • (二)JAVA使用POI操作excel
  • (四)软件性能测试
  • .NET : 在VS2008中计算代码度量值
  • .net core 3.0 linux,.NET Core 3.0 的新增功能
  • .NET8.0 AOT 经验分享 FreeSql/FreeRedis/FreeScheduler 均已通过测试
  • .NET建议使用的大小写命名原则
  • @Builder用法
  • @javax.ws.rs Webservice注解
  • @modelattribute注解用postman测试怎么传参_接口测试之问题挖掘
  • @ResponseBody
  • [ C++ ] template 模板进阶 (特化,分离编译)
  • [ 蓝桥杯Web真题 ]-Markdown 文档解析
  • [ 云计算 | AWS ] 对比分析:Amazon SNS 与 SQS 消息服务的异同与选择
  • [【JSON2WEB】 13 基于REST2SQL 和 Amis 的 SQL 查询分析器
  • [04] Android逐帧动画(一)