WebView2 (TEdgeBrowser) 更新了 Delphi 界面(例如 ICoreWebView2Controller2)
Posted
技术标签:
【中文标题】WebView2 (TEdgeBrowser) 更新了 Delphi 界面(例如 ICoreWebView2Controller2)【英文标题】:WebView2 (TEdgeBrowser) updated Delphi interface (e.g. ICoreWebView2Controller2) 【发布时间】:2021-06-15 00:03:04 【问题描述】:默认的 Delphi 10.4.2 TEdgeBrowser 界面目前只有原始版本的 WebView2。但是,似乎要在非白色背景上实现无闪烁加载,我们需要使用ICoreWebView2Controller2 设置背景颜色。如何从 Delphi 访问它(以向后兼容的方式)?我尝试从 Microsoft 更新的 WebView2 nuget 包中导入 .tlb,但是 Delphi 给出了 OLE 错误,所以我找不到使用新功能生成 Delphi WebView2 界面的方法。
【问题讨论】:
一种方法是下载Microsoft C/C++ SDK,查看头文件并将自己翻译成Delphi,这是您唯一感兴趣的界面。 【参考方案1】:要调用ICoreWebView2Controller2
方法,你必须先声明接口,然后在运行时使用QueryInterface
获取它的引用,最后调用方法。
在我从 Microsoft 头文件开始创建的一个小单元之后:
unit Ovb.WebView2;
interface
uses
WebView2;
const
IID_ICoreWebView2Controller2: TGUID = 'C979903E-D4CA-4228-92EB-47EE3FA96EAB';
type
COREWEBVIEW2_COLOR = packed record
A : BYTE;
R : BYTE;
B : BYTE;
G : BYTE;
end;
TCOREWEBVIEW2_COLOR = COREWEBVIEW2_COLOR;
PCOREWEBVIEW2_COLOR = ^COREWEBVIEW2_COLOR;
ICoreWebView2Controller2 = interface(ICoreWebView2Controller)
['C979903E-D4CA-4228-92EB-47EE3FA96EAB']
function get_DefaultBackgroundColor(backgroundColor : PCOREWEBVIEW2_COLOR) : HRESULT; stdcall;
function put_DefaultBackgroundColor(backgroundColor : TCOREWEBVIEW2_COLOR) : HRESULT; stdcall;
end;
implementation
end.
你可以像这样使用它:
procedure TEdgeViewForm.EdgeBrowser1CreateWebViewCompleted(
Sender : TCustomEdgeBrowser;
AResult : HRESULT);
var
Ctrl2 : ICoreWebView2Controller2;
BackColor : TCOREWEBVIEW2_COLOR;
HR : HRESULT;
begin
Sender.ControllerInterface.QueryInterface(IID_ICoreWebView2Controller2, Ctrl2);
if not Assigned(Ctrl2) then
raise Exception.Create('ICoreWebView2Controller2 not found');
// Select red background
BackColor.A := 255;
BackColor.R := 255;
BackColor.G := 0;
BackColor.B := 0;
HR := Ctrl2.put_DefaultBackgroundColor(BackColor);
if not SUCCEEDED(HR) then
raise Exception.Create('put_DefaultBackgroundColor failed');
end;
我已经使用 Embarcadero EdgeView 演示测试了我的代码。红色背景是可见的,所以我认为我的代码是正确的。
【讨论】:
很好的答案谢谢,似乎工作。 (虽然不幸的是不能解决我在深色主题中加载深色背景页面的闪烁问题) 另一种方法是下载/导入 tlb(包含在 c++ nuget 包中)并使用常量/接口作为参考,而不是手动移植标头。您仍然需要使用 QueryInterface 来获取接口。我使用这种方法来设置 cookie(ICoreWebView2_2 和 ICoreWebView2CookieManager)。感谢@fpiette 引导我走上正确的道路。 我偶然发现了这一点,因为我有与 OP 完全相同的问题。谢谢大家。我只是想补充一点,我在尝试通过 Delphi IDE 导入 TLB 时也遇到了 Ole 错误。但是使用命令行: tlibimp -P -Fe- -XR+ Webview2.tlb 工作正常。以上是关于WebView2 (TEdgeBrowser) 更新了 Delphi 界面(例如 ICoreWebView2Controller2)的主要内容,如果未能解决你的问题,请参考以下文章