string text = "return 'test';";
var webView = new Microsoft.Web.WebView2.WinForms.WebView2();
webView.EnsureCoreWebView2Async(null).RunSynchronously();
var srun = webView.CoreWebView2.ExecuteScriptAsync(text);
当我运行上面的代码时,EnsureCoreWebView2Async 收到此异常"Cannot change thread mode after it is set. (Exception from HRESULT: 0x80010106 (RPC_E_CHANGED_MODE))" i What do I need to do to run this with out a winform dlg in a console or windows service?
最佳答案
事实证明,关键是将 [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 将导致无限等待
目的。
实例存在。
关于c# - 如何在控制台应用程序中使用 WebView2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66699811/