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 WebView
	CreateCoreWebView2EnvironmentWithOptions(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 hWnd
		env->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 settings
			wil::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 window
			RECT bounds;
			::GetClientRect(hWnd, &bounds);
			webviewController->put_Bounds(bounds);

			// Schedule an async task to navigate to Bing
			webview->Navigate(L"https://www.bing.com/");

			// <NavigationEvents>
			// Step 4 - Navigation events
			// register an ICoreWebView2NavigationStartingEventHandler to cancel any non-https navigation
			EventRegistrationToken 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 object
			webview->AddScriptToExecuteOnDocumentCreated(L"Object.freeze(Object);", nullptr);
			// Schedule an async task to get the document URL
			webview->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 content
			webview->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 host
			webview->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

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部