From 1090a97c22fb33e07c213917f73f1ad6e2d0b23c Mon Sep 17 00:00:00 2001 From: Reilly Wood Date: Wed, 2 Mar 2022 20:54:57 -0800 Subject: [PATCH] Better error handling when initializing WV2 --- Program.cs | 29 +++++++++++++++++------------ 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/Program.cs b/Program.cs index d50a8f5..c910cc9 100644 --- a/Program.cs +++ b/Program.cs @@ -111,12 +111,21 @@ private static void OnSize(HWND hwnd, WPARAM wParam, int width, int height) private static async void CreateCoreWebView2(HWND hwnd) { - Console.WriteLine("Initializing WebView2..."); - try { + Console.WriteLine("Initializing WebView2..."); var environment = await CoreWebView2Environment.CreateAsync(null, null, null); _controller = await environment.CreateCoreWebView2ControllerAsync(hwnd); + + _controller.DefaultBackgroundColor = Color.Transparent; // avoids flash of white when page first renders + _controller.CoreWebView2.WebMessageReceived += CoreWebView2_WebMessageReceived; + _controller.CoreWebView2.SetVirtualHostNameToFolderMapping("minimalwebview.example", StaticFileDirectory, CoreWebView2HostResourceAccessKind.Allow); + PInvoke.GetClientRect(hwnd, out var hwndRect); + _controller.Bounds = new Rectangle(0, 0, hwndRect.right, hwndRect.bottom); + _controller.IsVisible = true; + _controller.CoreWebView2.Navigate("https://minimalwebview.example/index.html"); + + Console.WriteLine("WebView2 initialization succeeded."); } catch (WebView2RuntimeNotFoundException) { @@ -127,17 +136,13 @@ private static async void CreateCoreWebView2(HWND hwnd) //TODO: download WV2 bootstrapper from https://go.microsoft.com/fwlink/p/?LinkId=2124703 and run it } - throw; + Environment.Exit(1); + } + catch (Exception ex) + { + PInvoke.MessageBox(hwnd, $"Failed to initialize WebView2:{Environment.NewLine}{ex}", "Error", MESSAGEBOX_STYLE.MB_OK | MESSAGEBOX_STYLE.MB_ICONERROR); + Environment.Exit(1); } - Console.WriteLine("WebView2 initialization finished."); - - _controller.DefaultBackgroundColor = Color.Transparent; // avoids flash of white when page first renders - _controller.CoreWebView2.WebMessageReceived += CoreWebView2_WebMessageReceived; - _controller.CoreWebView2.SetVirtualHostNameToFolderMapping("minimalwebview.example", StaticFileDirectory, CoreWebView2HostResourceAccessKind.Allow); - PInvoke.GetClientRect(hwnd, out var hwndRect); - _controller.Bounds = new Rectangle(0, 0, hwndRect.right, hwndRect.bottom); - _controller.IsVisible = true; - _controller.CoreWebView2.Navigate("https://minimalwebview.example/index.html"); } private static async void CoreWebView2_WebMessageReceived(object sender, CoreWebView2WebMessageReceivedEventArgs e)