4 changed files with 116 additions and 61 deletions
@ -0,0 +1,71 @@ |
|||
using BBWY.Common.Models; |
|||
using Microsoft.Web.WebView2.Core; |
|||
using Microsoft.Web.WebView2.Wpf; |
|||
using System; |
|||
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<CoreWebView2WebMessageReceivedEventArgs> OnWebMessageReceived; |
|||
public Action<CoreWebView2NavigationCompletedEventArgs> OnNavigationCompleted; |
|||
public Action<CoreWebView2InitializationCompletedEventArgs> 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) |
|||
{ |
|||
isInitializationCompleted = true; |
|||
CoreWebView2InitializationCompleted?.Invoke(e); |
|||
} |
|||
|
|||
|
|||
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; |
|||
var wb2ProcessId = wb2.CoreWebView2.BrowserProcessId; |
|||
wb2.Dispose(); |
|||
int timeout = 10; |
|||
try |
|||
{ |
|||
while (System.Diagnostics.Process.GetProcessById(Convert.ToInt32(wb2ProcessId)) != null && timeout < 2000) |
|||
{ |
|||
System.Threading.Thread.Sleep(10); |
|||
timeout += 10; |
|||
} |
|||
} |
|||
catch { } |
|||
io.Directory.Delete(udf, true); |
|||
} |
|||
} |
|||
} |
|||
} |
Loading…
Reference in new issue