using System.Windows;
|
using System.Windows.Interop;
|
|
namespace Moli.Desktop.Interop;
|
|
public sealed class DisplayChangeMonitor : IDisposable
|
{
|
private HwndSource? _source;
|
private readonly SemaphoreSlim _singleFlight = new(1, 1);
|
private readonly int _debounceMs;
|
private CancellationTokenSource? _debounceCts;
|
private bool _disposed;
|
|
public event Func<Task>? DisplayChanged;
|
|
public DisplayChangeMonitor(int debounceMs = 500)
|
{
|
_debounceMs = debounceMs;
|
}
|
|
public void Start()
|
{
|
if (_source is not null)
|
{
|
return;
|
}
|
|
try
|
{
|
var parameters = new HwndSourceParameters("MoliDisplayChangeMonitor")
|
{
|
WindowStyle = 0,
|
ExtendedWindowStyle = 0,
|
ParentWindow = NativeMethods.HwndMessage,
|
};
|
|
_source = new HwndSource(parameters);
|
_source.AddHook(WndProc);
|
}
|
catch (InvalidOperationException)
|
{
|
_source = null;
|
}
|
}
|
|
public void Stop()
|
{
|
if (_source is null)
|
{
|
return;
|
}
|
|
_source.RemoveHook(WndProc);
|
_source.Dispose();
|
_source = null;
|
}
|
|
public void Dispose()
|
{
|
if (_disposed)
|
{
|
return;
|
}
|
|
_disposed = true;
|
Stop();
|
_debounceCts?.Cancel();
|
_debounceCts?.Dispose();
|
_singleFlight.Dispose();
|
}
|
|
private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
|
{
|
if (msg == NativeMethods.WmDisplayChange
|
|| msg == NativeMethods.WmSettingChange
|
|| msg == NativeMethods.WmDeviceChange)
|
{
|
OnDisplayChanged();
|
}
|
|
return IntPtr.Zero;
|
}
|
|
private async void OnDisplayChanged()
|
{
|
_debounceCts?.Cancel();
|
_debounceCts?.Dispose();
|
_debounceCts = new CancellationTokenSource();
|
var token = _debounceCts.Token;
|
|
try
|
{
|
await Task.Delay(_debounceMs, token).ConfigureAwait(false);
|
}
|
catch (OperationCanceledException)
|
{
|
return;
|
}
|
|
await _singleFlight.WaitAsync(CancellationToken.None).ConfigureAwait(false);
|
try
|
{
|
if (DisplayChanged is not null)
|
{
|
await DisplayChanged.Invoke().ConfigureAwait(false);
|
}
|
}
|
finally
|
{
|
_singleFlight.Release();
|
}
|
}
|
}
|