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 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

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
完全平方数是对某个整平方结果,例如4(2^2)、9(3^2)等。在学上,对于任意正整n,如果存在另一个整m使得m * m = n,则称n为完全平方数。 在 C++ 中处理完全平方数对(假设这里指的是寻找两个整,它们各自的平方相加等于目标值),我们可以创建一个函,该函接收一个整作为输入,并尝试找到所有满足条件的整组合。下面是具体的实现: ```cpp #include <iostream> #include <vector> using namespace std; void findSquarePairs(int targetSum) { for (int i = 0; i <= sqrt(targetSum); ++i) { // 避免不必要的循环迭代 int squareRoot = i * i; if (squareRoot > targetSum) break; // 如果当前平方根已经大于targetSum,则跳出循环 int otherPart = targetSum - squareRoot; int squareRootOfOtherPart = sqrt(otherPart); // 检查otherPart是否是一个完全平方数 if(squareRootOfOtherPart == floor(sqrt(otherPart))) { cout << "一对完全平方数:" << i << "^2 + " << squareRootOfOtherPart << "^2 = " << targetSum << endl; } } } // 使用示例 int main() { int target = 25; findSquarePairs(target); return 0; } ``` 在这个例子中,`findSquarePairs` 函首先遍历小于或等于 `sqrt(targetSum)` 的字,然后计算出剩余部分是否也是一个完全平方数。如果是的话,就找到了一组符合条件的对。 --- 相关问题 --- 1. 这种方法的时间复杂度是多少?如何优化? 2. 如果目标值很大,那么如何减少内存消耗? 3. 对于负或零的情况,这个算法应该如何修改?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值