using BBWY.Common.Models; using Microsoft.Web.WebView2.Core; using Microsoft.Web.WebView2.Wpf; using System; using System.Diagnostics; using System.Reflection; using io = System.IO; namespace BBWY.Client { public class WebView2Manager : IDenpendency { public WebView2 wb2 { get; private set; } private bool isInitializationCompleted; public WebView2Manager() { wb2 = new WebView2(); var wb2Setting = CoreWebView2Environment.CreateAsync(userDataFolder: io.Path.Combine(io.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "WebView2UserData")).Result; wb2.EnsureCoreWebView2Async(wb2Setting); wb2.CoreWebView2InitializationCompleted += Wb2_CoreWebView2InitializationCompleted; wb2.NavigationCompleted += Wb2_NavigationCompleted; wb2.WebMessageReceived += Wb2_WebMessageReceived; } public Action OnWebMessageReceived; public Action OnNavigationCompleted; public Action CoreWebView2InitializationCompleted; public bool IsInitializationCompleted { get => isInitializationCompleted; } private void Wb2_WebMessageReceived(object sender, CoreWebView2WebMessageReceivedEventArgs e) { OnWebMessageReceived?.Invoke(e); } private void Wb2_NavigationCompleted(object sender, CoreWebView2NavigationCompletedEventArgs e) { OnNavigationCompleted?.Invoke(e); } private void Wb2_CoreWebView2InitializationCompleted(object sender, CoreWebView2InitializationCompletedEventArgs e) { CoreWebView2InitializationCompleted?.Invoke(e); isInitializationCompleted = true; } public void Close() { if (wb2 != null && wb2.CoreWebView2 != null) { wb2.CoreWebView2InitializationCompleted -= Wb2_CoreWebView2InitializationCompleted; wb2.NavigationCompleted -= Wb2_NavigationCompleted; wb2.WebMessageReceived -= Wb2_WebMessageReceived; var udf = wb2.CoreWebView2.Environment.UserDataFolder; wb2.Dispose(); try { io.Directory.Delete(udf, true); } catch { } } } } }