如何在控制台应用程序中使用 WebView2

Aar*_*her 11 c# webview2

string text = "return 'test';";
var webView = new Microsoft.Web.WebView2.WinForms.WebView2();
webView.EnsureCoreWebView2Async(null).RunSynchronously();
var srun = webView.CoreWebView2.ExecuteScriptAsync(text);
Run Code Online (Sandbox Code Playgroud)

当我运行上面的代码 EnsureCoreWebView2Async 时出现此异常

“设置后无法更改线程模式。(HRESULT 异常:0x80010106 (RPC_E_CHANGED_MODE))”

我需要做什么才能在控制台或 Windows 服务中没有 winform dlg 的情况下运行它?

Aar*_*her 13

事实证明,关键是添加[STAThread]到功能中Main

class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        Application.EnableVisualStyles();
        Microsoft.Web.WebView2.WinForms.WebView2 webView21 = new Microsoft.Web.WebView2.WinForms.WebView2();

        var ecwTask = webView21.EnsureCoreWebView2Async(null);
        while (ecwTask.IsCompleted == false)
        {
            Application.DoEvents();
        };

        var scriptText = @"var test = function(){ return 'apple';}; test();";
        var srunTask = webView21.ExecuteScriptAsync(scriptText);
        while (srunTask.IsCompleted == false)
        {
            Application.DoEvents();
        };

        Console.WriteLine(srunTask.Result);
    }
}
Run Code Online (Sandbox Code Playgroud)

其他可能值得注意的项目,

  • 有时您需要设置应用程序的位数,因为使用 AnyCPU 会导致创建 WebView2 COM 对象时无限等待。
  • 您可能需要设置 webview2 源属性以强制实例存在。

  • 我刚刚了解到,**不要**使用`async Task Main()`,因为[它不适用于`STAThread`](https://github.com/dotnet/roslyn/issues/22112)。_(我花了 1 个小时才找到这个 bug。)_ (6认同)