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

标签 c# webview2

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 将导致无限等待
    目的。
  • 您可能需要设置 webview2 源属性来聚焦
    实例存在。
  • 关于c# - 如何在控制台应用程序中使用 WebView2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66699811/

    相关文章:

    wpf - 我如何检查是否使用 VB6 在 PC 上安装了 "Microsoft Edge WebView2 Runtime"或 "Microsoft Edge Insider Channels"金丝雀

    C# 如何正确使用CoreWebView2PrintSettings?

    .net - 相当于 WebView2 中的 WebBrowser.InvokeScript(String, Object[])

    c# - WinForms 数据绑定(bind)到自定义属性引发异常

    c# - 为什么当计时器倒计时时它从不在秒上显示 0?

    c# - 有可能制作一个可以在多种语言中使用的库吗?

    wpf - 将 WebView2 映射到相对路径

    c# - 在 WebResourceRequested 事件中为 WebView2 设置 cookie

    c# - Accord.Net 二项式概率质量函数结果与 Excel 结果不同

    c# - 多种类型的 Automapper 自定义值解析器重用