Web View2
Microsoft Edge WebView2 控件允许在本机应用中嵌入 web 技术(HTML、CSS 以及 JavaScript)。 WebView2 控件使用 Microsoft Edge 作为绘制引擎,以在本机应用中显示 web 内容。
MFC使用WebView2显示网页内容
1.1 新建项目
1.2 下载和安装Web View2包
通过菜单“项目”-“管理NuGet程序包”,下载相关包。
在“浏览”分页的左上角的搜索栏中,键入 Microsoft.Web.WebView2。 或者,复制并粘贴下面的单行代码块。 然后选择“ Microsoft.Web.WebView2”。以及在右侧选择对应的版本,然后点击按钮安装。
自动弹窗下载提示框,点击确定按钮。
输出下载的日志信息。
在项目的代码文件夹里会自动创建子文件夹packages,里面保存了下载的相关包文件夹:Microsoft.Web.WebView2.1.0.902.49 。
再下另一个包:Microsoft.Windows.ImplementationLibrary。
稍后,你将安装 Windows 实现库 (WIL) - 仅限标头的 C++ 库,通过适用于 Windows COM 编码模式的可读、类型安全的 C++ 接口,使 Windows 上的开发人员的生活更加轻松。 可通过 Visual Studio 中的 解决方案资源管理器 为项目安装此 Microsoft.Windows.ImplementationLibrary 包。
在 “NuGet” 窗口中,单击“ 浏览 ”选项卡。在左上角的搜索栏中,键入 Microsoft.Windows.ImplementationLibrary。 或者,复制并粘贴下面的单行代码块。 然后选择 “Microsoft.Windows.ImplementationLibrary”。
安装。
同样在项目文件夹里会下载子文件夹:Microsoft.Windows.ImplementationLibrary.1.0.191107.2 。
项目文件夹的文件packages.config:
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Microsoft.Web.WebView2" version="1.0.1901.177" targetFramework="native" />
<package id="Microsoft.Windows.ImplementationLibrary" version="1.0.230629.1" targetFramework="native" />
</packages>
1.3 添加依赖项
工程–>右键–>生成依赖项(B)。
1.4 添加Web控件
《1》添加变量和头文件
#include <iostream>
#include <wrl.h>
#include <wil/com.h>
#include "WebView2.h"
using namespace Microsoft::WRL;
// Pointer to WebViewController
static wil::com_ptr<ICoreWebView2Controller> webviewController;
// Pointer to WebView window
static wil::com_ptr<ICoreWebView2> webview;
《2》在OnCreate事件函数中添加代码
单文档或者多文档项目添加如下代码。
int CMFCApplication9View::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CView::OnCreate(lpCreateStruct) == -1)
return -1;
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 WebView
CreateCoreWebView2EnvironmentWithOptions(nullptr, nullptr, nullptr,
Callback<ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler>(
[hWnd](HRESULT result, ICoreWebView2Environment* env) -> HRESULT {
// Create a CoreWebView2Controller and get the a