如何在控制台应用程序中使用 WebView2
Posted
技术标签:
【中文标题】如何在控制台应用程序中使用 WebView2【英文标题】:How do I use WebView2 in a console application 【发布时间】:2021-06-16 08:50:44 【问题描述】: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 的情况下运行它?
【问题讨论】:
它可能需要一个 SynchronizationContext,因此它可以捕获它可以恢复到的执行上下文(它的调度程序)。RunSynchronously()
不能在这里使用。
【参考方案1】:
事实证明,关键是将 [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);
其他可能值得注意的项目,
有时您需要设置应用程序的位数,因为使用 AnyCPU 在创建 webview2 COM 时会导致无限等待 对象。 您可能需要将 webview2 源属性设置为 实例化。【讨论】:
以上是关于如何在控制台应用程序中使用 WebView2的主要内容,如果未能解决你的问题,请参考以下文章
调用 window.open 时如何在 WPF/WebView2 应用程序中创建自定义窗口?
如何在Visual Studio工具栏中添加WebView2控件?