Files
egwcapp/EgwControlCenter.App/BlazorForm.cs
T
2025-01-13 17:36:13 +01:00

365 lines
12 KiB
C#

using EgwControlCenter.Core;
using Microsoft.AspNetCore.Components.WebView.WindowsForms;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Win32;
using NLog;
using System.Diagnostics;
using System.Reflection;
namespace EgwControlCenter.App
{
public partial class BlazorForm : Form
{
#region Public Constructors
public BlazorForm()
{
InitializeComponent();
ServiceInit();
CleanOldTrayIcons();
InitBlazorView();
StartTimer();
StartLastAsync();
}
#endregion Public Constructors
#region Private Fields
/// <summary>
/// Classe logger
/// </summary>
private static Logger Log = LogManager.GetCurrentClassLogger();
private bool forceClose = false;
private Size minSize = new Size(676, 409);
/// <summary>
/// Periodo di blocco invio nuove notifiche se ci sono + update...
/// </summary>
private int VetoNewNotifySec = 15;
#endregion Private Fields
#region Private Properties
private static AppControlService MainAppControlService { get; set; } = null!;
private string AppName => CurrAssembly.Name ?? "EgalWare ACC";
private System.Reflection.AssemblyName CurrAssembly { get; set; } = new System.Reflection.AssemblyName();
/// <summary>
/// Ultima visualizzazione messaggio...
/// </summary>
private DateTime lastMsqShown { get; set; } = DateTime.MinValue;
private Size lastSize { get; set; } = new Size(636, 409);
#endregion Private Properties
#region Private Methods
private void BlazorForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (forceClose)
{
MainAppControlService.EA_StatusUpdated -= MainAppControlService_EA_StatusUpdated;
MainAppControlService.EA_ConfigUpdated -= MainAppControlService_EA_ConfigUpdated;
timerCheck.Stop();
timerCheck.Dispose();
}
else
{
e.Cancel = true;
// reimposto size...
Size = lastSize;
SetPosition();
SendToTray();
}
}
private async void BlazorForm_Load(object sender, EventArgs e)
{
SetPosition();
// aspetto e poi mando a tray...
await Task.Delay(500);
SendToTray();
}
private void BlazorForm_Resize(object sender, EventArgs e)
{
CheckFormVisibility();
}
/// <summary>
/// Verifica stato windows (minimized/normal) e visibilità con tray...
/// </summary>
private void CheckFormVisibility()
{
// controllo cosa devo mostrare...
if (WindowState == FormWindowState.Minimized)
{
SendToTray();
}
notifyIcon1.Visible = true;
}
private void CleanOldTrayIcons()
{
Assembly assembly = Assembly.GetExecutingAssembly();
string startDir = Path.GetDirectoryName(assembly.Location)!;
string appPath = assembly.ManifestModule.FullyQualifiedName.Replace("dll", "exe");
RegistryKey? key = Registry.CurrentUser.OpenSubKey(@"Control Panel\NotifyIconSettings", true);
if (key != null)
{
foreach (string subKeyName in key.GetSubKeyNames())
{
RegistryKey? subKey = key.OpenSubKey(subKeyName);
if (subKey != null)
{
string executablePath = subKey.GetValue("ExecutablePath") as string ?? "";
// cerco solo le chiavi di EgwControlCenter.App.exe
if (!string.IsNullOrEmpty(executablePath))
{
if (executablePath.EndsWith("EgwControlCenter.App.exe") || executablePath.Contains("EgwControlCenter"))
{
// se il path NON E' quello da cui sta girando il software -->
// elimino chiave registro...
if (!executablePath.Equals(appPath))
{
key.DeleteSubKey(subKeyName);
}
}
}
}
}
}
else
{
Console.WriteLine("NotifyIconSettings key not found.");
}
}
/// <summary>
/// crea menù tray x applicazione
/// </summary>
private void CreateTrayMenu()
{
// Fix testi menù tray...
trayMenu.Items.Clear();
// aggiungo azioni con tasto DX
trayMenu.Items.Add("Show EgalWare ACC");
trayMenu.Items.Add("Restart EgalWare ACC");
trayMenu.Items.Add("Close EgalWare ACC");
}
private void DoDisplay()
{
Show();
WindowState = FormWindowState.Normal;
}
/// <summary>
/// Chiamata controllo status update
/// </summary>
private async Task ForceReload()
{
await MainAppControlService.DoFullCheckAsync(true);
}
private void InitBlazorView()
{
Stopwatch sw = new Stopwatch();
sw.Start();
CurrAssembly = System.Reflection.Assembly.GetExecutingAssembly().GetName();
Log.Trace($"EgalWare's AppControlCenter Init, v.{CurrAssembly.Version}");
// sistemo grafica TRAY ICON
SetupTrayIcon();
CreateTrayMenu();
try
{
Log.Trace($"TrayMenu OK | {sw.ElapsedMilliseconds}ms");
var services = new ServiceCollection();
Log.Trace($"Add ServiceCollection | {sw.ElapsedMilliseconds}ms");
services.AddWindowsFormsBlazorWebView();
Log.Trace($"Add AddWindowsFormsBlazorWebView | {sw.ElapsedMilliseconds}ms");
services.AddSingleton<AppControlService>(MainAppControlService);
Log.Trace($"Add AppControlService | {sw.ElapsedMilliseconds}ms");
blazorWebView1.HostPage = "wwwroot\\index.html";
blazorWebView1.Services = services.BuildServiceProvider();
blazorWebView1.RootComponents.Add<MainBlazor>("#app");
Log.Trace($"Add MainBlazor | {sw.ElapsedMilliseconds}ms");
}
catch (Exception exc)
{
Log.Error($"Exception during setartup{Environment.NewLine}{exc}");
}
}
/// <summary>
/// Riavvio il timer...
/// </summary>
/// <exception cref="NotImplementedException"></exception>
private void MainAppControlService_EA_ConfigUpdated()
{
timerCheck.Stop();
StartTimer();
}
/// <summary>
/// Verifica se ci siano update da mostrare come notifica in tray
/// </summary>
/// <exception cref="NotImplementedException"></exception>
private void MainAppControlService_EA_StatusUpdated()
{
// notifica ballontip se ho aggiornamenti...
DateTime adesso = DateTime.Now;
// mostro se non ne ho ricevuti altri da almeno 10 sec...
if (WindowState != FormWindowState.Normal && adesso > lastMsqShown.AddSeconds(VetoNewNotifySec))
{
// salvo che ho mostrato msg
lastMsqShown = adesso;
// mostro notifica...
notifyIcon1.BalloonTipTitle = "EgalWare's App Control Center";
notifyIcon1.BalloonTipText = "Update found!";
notifyIcon1.BalloonTipIcon = ToolTipIcon.Warning;
notifyIcon1.BalloonTipClicked += NotifyIcon1_BalloonTipClicked;
notifyIcon1.ShowBalloonTip(200);
}
}
private void NotifyIcon1_BalloonTipClicked(object? sender, EventArgs e)
{
DoDisplay();
}
/// <summary>
/// doppio click su tray icon
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void notifyIcon1_DoubleClick(object sender, EventArgs e)
{
if (WindowState == FormWindowState.Minimized)
{
DoDisplay();
}
else
{
SendToTray();
}
}
private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button != MouseButtons.Right)
{
if (WindowState == FormWindowState.Minimized)
{
DoDisplay();
}
else
{
SendToTray();
}
}
}
/// <summary>
/// Gestisce "andata nel tray" della form
/// </summary>
private void SendToTray()
{
if (!notifyIcon1.Visible)
{
notifyIcon1.BalloonTipTitle = AppName;
notifyIcon1.BalloonTipText = $"{AppName} running on tray";
notifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
notifyIcon1.BalloonTipClicked += NotifyIcon1_BalloonTipClicked;
notifyIcon1.Visible = true;
notifyIcon1.ShowBalloonTip(100);
}
WindowState = FormWindowState.Minimized;
Hide();
}
private void ServiceInit()
{
//init preliminare servizio controllo
MainAppControlService = new AppControlService();
MainAppControlService.EA_StatusUpdated += MainAppControlService_EA_StatusUpdated;
MainAppControlService.EA_ConfigUpdated += MainAppControlService_EA_ConfigUpdated;
}
private void SetPosition()
{
// posiziono in basso a sx...
Rectangle workArea = Screen.GetWorkingArea(this);
this.Location = new Point(workArea.Right - lastSize.Width, workArea.Bottom - lastSize.Height);
}
private void SetupTrayIcon()
{
// fix icon!
notifyIcon1.Text = $"EgalWare's AppControlCenter | {CurrAssembly.Version}";
}
/// <summary>
/// init ultime attività async
/// </summary>
private void StartLastAsync()
{
var pUpd = Task.Run(async () =>
{
await ForceReload();
});
pUpd.Wait();
}
private void StartTimer()
{
timerCheck.Interval = (MainAppControlService.RefreshPeriod * 1000);
// sistemo timer
timerCheck.Start();
}
private async void timerCheck_Tick(object sender, EventArgs e)
{
// esegue controllo locale ed eventualmente remoto se scaduto...
await MainAppControlService.DoFullCheckAsync(false);
}
/// <summary>
/// click su menù contestuale in tray
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void trayMenu_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
if (e != null && e.ClickedItem != null && !string.IsNullOrEmpty(e.ClickedItem.Text))
{
if (e.ClickedItem.Text.StartsWith("Close"))
{
// chiudo!
forceClose = true;
Close();
}
else if (e.ClickedItem.Text.StartsWith("Restart"))
{
forceClose = true;
Application.Restart();
Environment.Exit(0);
}
else if (e.ClickedItem.Text.StartsWith("Show"))
{
Show();
WindowState = FormWindowState.Normal;
}
}
}
#endregion Private Methods
}
}