繁体   English   中英

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

[英]How do I use WebView2 in a console application

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 function。

    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 object 时,使用 AnyCPU 会导致无限等待。
  • 您可能需要设置 webview2 源属性以使实例存在。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM