Skip to content

Commit

Permalink
Better error handling when initializing WV2
Browse files Browse the repository at this point in the history
  • Loading branch information
rgwood committed Mar 3, 2022
1 parent da44609 commit 1090a97
Showing 1 changed file with 17 additions and 12 deletions.
29 changes: 17 additions & 12 deletions Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
{
Expand All @@ -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)
Expand Down

0 comments on commit 1090a97

Please sign in to comment.