我采用了最新版本的 Microsoft.Web.WebView2(0.9.515-预发布)并将其添加到测试 C# WinForms 应用程序中。我使用VS 2019,.NET框架是4.7.2。
将WebView2控件放置在窗体上,编译并运行。应用程序在加载时崩溃,位于 Form1.designer.cs 中的以下位置。
// webView21
//
this.webView21.Location = new System.Drawing.Point(153, 66);
this.webView21.Name = "webView21";
this.webView21.Size = new System.Drawing.Size(492, 253);
this.webView21.Source = new System.Uri("about:blank", System.UriKind.Absolute);
this.webView21.TabIndex = 0;
this.webView21.Text = "webView21";
this.webView21.ZoomFactor = 1D;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.webView21); //CRASHED HERE WITH BELOW EXCEPTION -
当我在发布模式下运行它时,得到以下异常跟踪 -
System.NullReferenceException:未将对象引用设置为对象的实例。
at Microsoft.Web.WebView2.WinForms.WebView2.OnVisibleChanged(EventArgs e)
at System.Windows.Forms.Control.OnParentVisibleChanged(EventArgs e)
at System.Windows.Forms.Control.OnVisibleChanged(EventArgs e)
at System.Windows.Forms.ScrollableControl.OnVisibleChanged(EventArgs e)
at System.Windows.Forms.Form.OnVisibleChanged(EventArgs e)
at System.Windows.Forms.Control.WmShowWindow(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
at System.Windows.Forms.Form.WmShowWindow(Message& m)
at System.Windows.Forms.Form.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
如果我使用最新稳定版本的 WebView2 (v 0.9.488),它会抛出编译错误,因为它不反映 Microsoft.Web
请让我知道如何修复此错误。非常感谢您的帮助。 8 个月前遇到了这个问题,但我希望微软现在已经超越了这个问题。如何在 C# Windows 应用程序中使用 Microsoft Edge WebView2 控件 https://stackoverflow.com/questions/57853644/how-can-i-use-the-microsoft-edge-webview2-control-in-c-sharp-windows-application
Microsoft 创建的示例解决方案也有适用于 WinForms 的 C# 版本。https://github.com/MicrosoftEdge/WebView2Samples https://github.com/MicrosoftEdge/WebView2Samples
也尝试了微软提供的这个示例。它也崩溃了。https://learn.microsoft.com/en-us/microsoft-edge/webview2/gettingstarted/winforms https://learn.microsoft.com/en-us/microsoft-edge/webview2/gettingstarted/winforms