Search code examples
delphiwebview2

WebView2 (TEdgeBrowser) updated Delphi interface (e.g. ICoreWebView2Controller2)


The default Delphi 10.4.2 TEdgeBrowser interface is currently only the original-release WebView2. However, it seems that to have flicker-free load on non-white backgrounds we need to set the background color using ICoreWebView2Controller2. How to access this (in a backwards-compatible way) from Delphi? I have tried importing the .tlb from Microsoft's updated WebView2 nuget bundle, however Delphi gives an OLE error, so I cannot find a way to generate a Delphi WebView2 interface with the new functions.


Solution

  • To call the ICoreWebView2Controller2 methods, you have to first declare the interface and then at run time use QueryInterface to get a reference on it and finally call the method.

    Here after a small unit that I created starting from Microsoft header file:

    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.
    

    You can use it for example like this:

    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;
    

    I have tested my code using Embarcadero EdgeView demo. The red background is visible so I consider my code as correct.