Get started with WebView2 in WinForms apps

官方的示例https://github.com/MicrosoftEdge/WebView2Samples/tree/master/GettingStartedGuides/WinForms_GettingStarted中的一些问题

  • WebView2版本过低,需要升级一下
  • 使用的是.NET Framework,而不是.NET Core

打包工作

只须创建一个新的C#版的Windows Application Packaging Project,然后添加一个到上述WinForms工程的引用即可。

WindowsAppSdk提供了Package your app using single-project MSIX,但是需要安装NuGet包Microsoft.WindowsApp.Sdk。 否则就会出现Need recipe file,因为没有生成appxrecipe。 这是在Microsoft.WindowsApp.Sdk,的buil\Microsoft.Build.Msix.Packaging.targets中创建的。

AddHostObjectToScript

只须按照WebView2 .NET CoreWebView2.AddHostObjectToScript(String, Object) Method的来即可。

无须WinRT版本的WebView2的ComInterop:

    var interop = (ICoreWebView2Interop)(object)MyWebView.CoreWebView2;
    interop.AddHostObjectToScript("bridge", new Bridge());

(完)