MFC使用 Microsoft Edge Web View2 欣赏器控件显示网页

种地  论坛元老 | 2024-11-30 15:22:05 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 1092|帖子 1092|积分 3276

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:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <packages>
  3.   <package id="Microsoft.Web.WebView2" version="1.0.1901.177" targetFramework="native" />
  4.   <package id="Microsoft.Windows.ImplementationLibrary" version="1.0.230629.1" targetFramework="native" />
  5. </packages>
复制代码
1.3 添加依赖项

工程–>右键–>生成依赖项(B)。


1.4 添加Web控件

《1》添加变量和头文件

  1. #include <iostream>
  2. #include <wrl.h>
  3. #include <wil/com.h>
  4. #include "WebView2.h"
  5. using namespace Microsoft::WRL;
  6. // Pointer to WebViewController
  7. static wil::com_ptr<ICoreWebView2Controller> webviewController;
  8. // Pointer to WebView window
  9. static wil::com_ptr<ICoreWebView2> webview;
复制代码

《2》在OnCreate变乱函数中添加代码

单文档或者多文档项目添加如下代码。
  1. int CMFCApplication9View::OnCreate(LPCREATESTRUCT lpCreateStruct)
  2. {
  3.         if (CView::OnCreate(lpCreateStruct) == -1)
  4.                 return -1;
  5.         HWND hWnd = this->m_hWnd;
  6.         // TODO:  在此添加您专用的创建代码
  7.         // <-- WebView2 sample code starts here -->
  8.         // Step 3 - Create a single WebView within the parent window
  9.         // Locate the browser and set up the environment for WebView
  10.         CreateCoreWebView2EnvironmentWithOptions(nullptr, nullptr, nullptr,
  11.                 Callback<ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler>(
  12.                         [hWnd](HRESULT result, ICoreWebView2Environment* env) -> HRESULT {
  13.                 // Create a CoreWebView2Controller and get the associated CoreWebView2 whose parent is the main window hWnd
  14.                 env->CreateCoreWebView2Controller(hWnd, Callback<ICoreWebView2CreateCoreWebView2ControllerCompletedHandler>(
  15.                         [hWnd](HRESULT result, ICoreWebView2Controller* controller) -> HRESULT {
  16.                         if (controller != nullptr) {
  17.                                 webviewController = controller;
  18.                                 webviewController->get_CoreWebView2(&webview);
  19.                         }
  20.                         // Add a few settings for the webview
  21.                         // The demo step is redundant since the values are the default settings
  22.                         wil::com_ptr<ICoreWebView2Settings> settings;
  23.                         webview->get_Settings(&settings);
  24.                         settings->put_IsScriptEnabled(TRUE);
  25.                         settings->put_AreDefaultScriptDialogsEnabled(TRUE);
  26.                         settings->put_IsWebMessageEnabled(TRUE);
  27.                         // Resize WebView to fit the bounds of the parent window
  28.                         RECT bounds;
  29.                         ::GetClientRect(hWnd, &bounds);
  30.                         webviewController->put_Bounds(bounds);
  31.                         // Schedule an async task to navigate to Bing
  32.                         webview->Navigate(L"https://www.bing.com/");
  33.                         // <NavigationEvents>
  34.                         // Step 4 - Navigation events
  35.                         // register an ICoreWebView2NavigationStartingEventHandler to cancel any non-https navigation
  36.                         EventRegistrationToken token;
  37.                         webview->add_NavigationStarting(Callback<ICoreWebView2NavigationStartingEventHandler>(
  38.                                 [](ICoreWebView2* webview, ICoreWebView2NavigationStartingEventArgs* args) -> HRESULT {
  39.                                 wil::unique_cotaskmem_string uri;
  40.                                 args->get_Uri(&uri);
  41.                                 std::wstring source(uri.get());
  42.                                 if (source.substr(0, 5) != L"https") {
  43.                                         args->put_Cancel(true);
  44.                                 }
  45.                                 return S_OK;
  46.                         }).Get(), &token);
  47.                         // </NavigationEvents>
  48.                         // <Scripting>
  49.                         // Step 5 - Scripting
  50.                         // Schedule an async task to add initialization script that freezes the Object object
  51.                         webview->AddScriptToExecuteOnDocumentCreated(L"Object.freeze(Object);", nullptr);
  52.                         // Schedule an async task to get the document URL
  53.                         webview->ExecuteScript(L"window.document.URL;", Callback<ICoreWebView2ExecuteScriptCompletedHandler>(
  54.                                 [](HRESULT errorCode, LPCWSTR resultObjectAsJson) -> HRESULT {
  55.                                 LPCWSTR URL = resultObjectAsJson;
  56.                                 //doSomethingWithURL(URL);
  57.                                 return S_OK;
  58.                         }).Get());
  59.                         // </Scripting>
  60.                         // <CommunicationHostWeb>
  61.                         // Step 6 - Communication between host and web content
  62.                         // Set an event handler for the host to return received message back to the web content
  63.                         webview->add_WebMessageReceived(Callback<ICoreWebView2WebMessageReceivedEventHandler>(
  64.                                 [](ICoreWebView2* webview, ICoreWebView2WebMessageReceivedEventArgs* args) -> HRESULT {
  65.                                 wil::unique_cotaskmem_string message;
  66.                                 args->TryGetWebMessageAsString(&message);
  67.                                 // processMessage(&message);
  68.                                 webview->PostWebMessageAsString(message.get());
  69.                                 return S_OK;
  70.                         }).Get(), &token);
  71.                         // Schedule an async task to add initialization script that
  72.                         // 1) Add an listener to print message from the host
  73.                         // 2) Post document URL to the host
  74.                         webview->AddScriptToExecuteOnDocumentCreated(
  75.                                 L"window.chrome.webview.addEventListener(\'message\', event => alert(event.data));" \
  76.                                 L"window.chrome.webview.postMessage(window.document.URL);",
  77.                                 nullptr);
  78.                         // </CommunicationHostWeb>
  79.                         return S_OK;
  80.                 }).Get());
  81.                 return S_OK;
  82.         }).Get());
  83.         // <-- WebView2 sample code ends here -->
  84.         return 0;
  85. }
复制代码
如果是对话框项目,则在OnInitDialog变乱函数中添加代码。
  1. BOOL CMFCWebView2Dlg::OnInitDialog()
  2. {
  3.         CDialogEx::OnInitDialog();
  4.         // 将“关于...”菜单项添加到系统菜单中。
  5.         // IDM_ABOUTBOX 必须在系统命令范围内。
  6.         ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
  7.         ASSERT(IDM_ABOUTBOX < 0xF000);
  8.         CMenu* pSysMenu = GetSystemMenu(FALSE);
  9.         if (pSysMenu != nullptr)
  10.         {
  11.                 BOOL bNameValid;
  12.                 CString strAboutMenu;
  13.                 bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
  14.                 ASSERT(bNameValid);
  15.                 if (!strAboutMenu.IsEmpty())
  16.                 {
  17.                         pSysMenu->AppendMenu(MF_SEPARATOR);
  18.                         pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
  19.                 }
  20.         }
  21.         // 设置此对话框的图标。  当应用程序主窗口不是对话框时,框架将自动
  22.         //  执行此操作
  23.         SetIcon(m_hIcon, TRUE);                        // 设置大图标
  24.         SetIcon(m_hIcon, FALSE);                // 设置小图标
  25.    
  26.     CoInitialize(NULL);
  27.         HWND hWnd = this->m_hWnd;
  28.         // TODO:  在此添加您专用的创建代码
  29.         // <-- WebView2 sample code starts here -->
  30.         // Step 3 - Create a single WebView within the parent window
  31.         // Locate the browser and set up the environment for WebView
  32.         CreateCoreWebView2EnvironmentWithOptions(nullptr, nullptr, nullptr,
  33.                 Callback<ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler>(
  34.                         [hWnd](HRESULT result, ICoreWebView2Environment* env) -> HRESULT
  35.                         {
  36.                                 // Create a CoreWebView2Controller and get the associated CoreWebView2 whose parent is the main window hWnd
  37.                                 env->CreateCoreWebView2Controller(hWnd, Callback<ICoreWebView2CreateCoreWebView2ControllerCompletedHandler>(
  38.                                         [hWnd](HRESULT result, ICoreWebView2Controller* controller) -> HRESULT {
  39.                                                 if (controller != nullptr) {
  40.                                                         webviewController = controller;
  41.                                                         webviewController->get_CoreWebView2(&webview);
  42.                                                 }
  43.                                                 // Add a few settings for the webview
  44.                                                 // The demo step is redundant since the values are the default settings
  45.                                                 wil::com_ptr<ICoreWebView2Settings> settings;
  46.                                                 webview->get_Settings(&settings);
  47.                                                 settings->put_IsScriptEnabled(TRUE);
  48.                                                 settings->put_AreDefaultScriptDialogsEnabled(TRUE);
  49.                                                 settings->put_IsWebMessageEnabled(TRUE);
  50.                                                 // Resize WebView to fit the bounds of the parent window
  51.                                                 RECT bounds;
  52.                                                 ::GetClientRect(hWnd, &bounds);
  53.                                                 webviewController->put_Bounds(bounds);
  54.                                                 // Schedule an async task to navigate to Bing
  55.                                                 webview->Navigate(L"https://www.bing.com/");
  56.                                                 // <NavigationEvents>
  57.                                                 // Step 4 - Navigation events
  58.                                                 // register an ICoreWebView2NavigationStartingEventHandler to cancel any non-https navigation
  59.                                                 EventRegistrationToken token;
  60.                                                 webview->add_NavigationStarting(Callback<ICoreWebView2NavigationStartingEventHandler>(
  61.                                                         [](ICoreWebView2* webview, ICoreWebView2NavigationStartingEventArgs* args) -> HRESULT {
  62.                                                                 wil::unique_cotaskmem_string uri;
  63.                                                                 args->get_Uri(&uri);
  64.                                                                 std::wstring source(uri.get());
  65.                                                                 if (source.substr(0, 5) != L"https") {
  66.                                                                         args->put_Cancel(true);
  67.                                                                 }
  68.                                                                 return S_OK;
  69.                                                         }).Get(), &token);
  70.                                                 // </NavigationEvents>
  71.                                                 // <Scripting>
  72.                                                 // Step 5 - Scripting
  73.                                                 // Schedule an async task to add initialization script that freezes the Object object
  74.                                                 webview->AddScriptToExecuteOnDocumentCreated(L"Object.freeze(Object);", nullptr);
  75.                                                 // Schedule an async task to get the document URL
  76.                                                 webview->ExecuteScript(L"window.document.URL;", Callback<ICoreWebView2ExecuteScriptCompletedHandler>(
  77.                                                         [](HRESULT errorCode, LPCWSTR resultObjectAsJson) -> HRESULT {
  78.                                                                 LPCWSTR URL = resultObjectAsJson;
  79.                                                                 //doSomethingWithURL(URL);
  80.                                                                 return S_OK;
  81.                                                         }).Get());
  82.                                                 // </Scripting>
  83.                                                 // <CommunicationHostWeb>
  84.                                                 // Step 6 - Communication between host and web content
  85.                                                 // Set an event handler for the host to return received message back to the web content
  86.                                                 webview->add_WebMessageReceived(Callback<ICoreWebView2WebMessageReceivedEventHandler>(
  87.                                                         [](ICoreWebView2* webview, ICoreWebView2WebMessageReceivedEventArgs* args) -> HRESULT {
  88.                                                                 wil::unique_cotaskmem_string message;
  89.                                                                 args->TryGetWebMessageAsString(&message);
  90.                                                                 // processMessage(&message);
  91.                                                                 webview->PostWebMessageAsString(message.get());
  92.                                                                 return S_OK;
  93.                                                         }).Get(), &token);
  94.                                                 // Schedule an async task to add initialization script that
  95.                                                 // 1) Add an listener to print message from the host
  96.                                                 // 2) Post document URL to the host
  97.                                                 webview->AddScriptToExecuteOnDocumentCreated(
  98.                                                         L"window.chrome.webview.addEventListener(\'message\', event => alert(event.data));" \
  99.                                                         L"window.chrome.webview.postMessage(window.document.URL);",
  100.                                                         nullptr);
  101.                                                 // </CommunicationHostWeb>
  102.                                                 return S_OK;
  103.                                         }).Get());
  104.                                 return S_OK;
  105.                         }).Get());
  106.         return TRUE;  // 除非将焦点设置到控件,否则返回 TRUE
  107. }
复制代码
《3》在OnSize变乱函数中添加代码

  1. void CMFCApplication9View::OnSize(UINT nType, int cx, int cy)
  2. {
  3.         CView::OnSize(nType, cx, cy);
  4.         // TODO: 在此处添加消息处理程序代码
  5.         if (webviewController != nullptr) {
  6.                 RECT bounds;
  7.                 GetClientRect(&bounds);
  8.                 webviewController->put_Bounds(bounds);
  9.         };
  10. }
复制代码

1.5 运行效果

《1》依赖动态库整理

在 packages 目录下搜索缺少的依赖动态库。

搜索 "WebView2Loader.dll" ,拷贝到项目Debug目录下。

《2》运行程序


《3》百度导航


1.6 注意事项

在代码开始和结束的位置添加如下代码。
  1. //初始化位置
  2. CoInitialize(NULL);
  3. //程序销毁
  4. CoUninitialize();
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

种地

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表