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

问题描述

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

当我运行上面的代码时,EnsureCoreWebView2Async 得到这个异常

“设置后无法更改线程模式。(来自 HRESULT 的异常: 0x80010106 (RPC_E_CHANGED_MODE))" 一世 我需要做什么才能在控制台或 Windows 服务中没有 winform dlg 的情况下运行它?

解决方法

事实证明,关键是将 [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);
}
}

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

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