How do I use WebView2 in a console application

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

When I run the above code EnsureCoreWebView2Async is getting this exception

"Cannot change thread mode after it is set. (Exception from HRESULT: 0x80010106 (RPC_E_CHANGED_MODE))"

What do I need to do to run this with out a winform dlg in a console or windows service?

1 Answers

It turns out the key thing is to a[STAThread] to the 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);
}
}

Other items that maybe note worthy,

  • Sometimes you need to set the bitness of the application because use of AnyCPU will cause an infanite wait when creating the webview2 COM object.
  • You may need to set the webview2 source property to foce the instance into existance.
Related