【发布时间】:2020-12-27 00:26:32
【问题描述】:
我正在使用 Visual Studio 2015 版本 14.0.23107.0。项目的目标平台是10.0.17763.0。
我已阅读this 文章,并做了第一步。我从GitHub 下载了 webview2 解决方案并在 Visual Studio 中打开它。然后,通过 git NuGet 我成功添加了 Windows 实现库包(版本 1.0.200902.2)和 WebView2 包(版本 0.9.579)。
然后,我在HelloWebView.cpp 中添加了
#include "WebView2.h"
一开始我无法编译它。 HelloWebView.cpp 和 WebView2.h 中没有错误。问题出在 Windows 实现库中。
询问俄语堆栈溢出I got the solution - 不包含 Windows 实现库,而是包含 ATL,并且
static wil::com_ptr<ICoreWebView2Controller> webviewController;
// Pointer to WebView window
static wil::com_ptr<ICoreWebView2> webviewWindow;
替换为
static CComPtr<ICoreWebView2Controller> webviewController;
// Pointer to WebView window
static CComPtr <ICoreWebView2> webviewWindow;
并删除using::Microsoft;
之后,项目编译,但链接失败 - LINK1158 error, can’t run rc.exe。解决方案是here(需要将rc.exe和rcdll.dll复制到某个文件夹)。
现在它可以编译并工作了。
所以,我从文章中进入下一步并添加代码以创建 webview 和打开 url,但再次无法编译它。只有一个问题 - 错过了 Windows 实现库中的 Callback 模板类。
所以我唯一需要做的,要彻底解决问题,就是提供我自己的模板Callback 类。但是该怎么做呢?
当前临界区(回调被标记为错误)
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(&webviewWindow);
}
// Add a few settings for the webview
// The demo step is redundant since the values are the default settings
ICoreWebView2Settings* Settings;
webviewWindow->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
webviewWindow->Navigate(L"https://www.bing.com/");
// Step 4 - Navigation events
// Step 5 - Scripting
// Step 6 - Communication between host and web content
return S_OK;
}).Get());
return S_OK;
}).Get());
Callback 来自 Windows 实现库的声明:
template<typename TDelegateInterface, typename TLambda>
ComPtr<typename Details::DelegateArgTraitsHelper<TDelegateInterface>::Interface> Callback(TLambda&& callback) throw()
{
using DelegateHelper = Details::DelegateArgTraitsHelper<TDelegateInterface>;
return DelegateHelper::Traits::template Callback<TDelegateInterface, typename DelegateHelper::Interface>(Details::Forward<TLambda>(callback));
}
我不知道,我不太喜欢 c++11,14 的特性,我没有经常使用 lambda,而且我(打赌不仅是我)也不喜欢模板之类的东西。
也许只是在之后调用代码?
【问题讨论】:
-
我按照文章尝试复现你的问题,但是没有出现你提到的问题。我用的是vs2019,vs2017也能成功编译代码。
-
对了,老版本的VS可能还有其他问题。我建议你在调试之前使用VS2017或VS2019。
-
@StriveSun-MSFT 这很不舒服,我需要用 VS15 做所有尝试
标签: c++ winapi webview com windows-10-sdk