using System.Runtime.InteropServices; namespace Ads.Desktop; /// Shares the Windows desktop UI lease with Flutter, including tray mode. internal sealed class DesktopInstance : IDisposable { private readonly Mutex mutex; private readonly EventWaitHandle activation; private RegisteredWaitHandle? registration; public bool Primary { get; } public DesktopInstance() { activation = new EventWaitHandle(false, EventResetMode.AutoReset, @"Local\TTSTD.ADS.Desktop.Activate"); mutex = new Mutex(true, @"Local\TTSTD.ADS.Desktop.Instance", out var primary); Primary = primary; } public void Activate() { AllowSetForegroundWindow(uint.MaxValue); activation.Set(); } public void Listen(Action show) => registration = ThreadPool.RegisterWaitForSingleObject(activation, (_, _) => show(), null, Timeout.Infinite, false); public void Dispose() { registration?.Unregister(null); if (Primary) mutex.ReleaseMutex(); mutex.Dispose(); activation.Dispose(); } [DllImport("user32.dll")] private static extern bool AllowSetForegroundWindow(uint processId); }