Debounce window changed events for significantly improved consistency when switching apps through the start menu

This commit is contained in:
dlprows 2023-10-04 09:27:25 -06:00
parent d1df235af0
commit 48161b5c2e

View File

@ -39,12 +39,24 @@ namespace FocusVolumeControl
public event Action WindowChanged; public event Action WindowChanged;
private void WinEventProc(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime) CancellationTokenSource? _cancellationTokenSource = null;
private async void WinEventProc(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime)
{ {
try try
{ {
//debounce the window changed events by 100 ms because if you click mouse over an application on the start bar
//and then click on the preview window, it will quickly go from current -> fallback -> new app
//which can often result in it getting stuck on the fallback app
_cancellationTokenSource?.Cancel();
_cancellationTokenSource = new CancellationTokenSource();
await Task.Delay(100, _cancellationTokenSource.Token);
WindowChanged?.Invoke(); WindowChanged?.Invoke();
} }
catch (TaskCanceledException)
{
//ignored
}
catch (Exception ex) catch (Exception ex)
{ {
Logger.Instance.LogMessage(TracingLevel.ERROR, $"Unexpected Error in EventHandler:\n {ex}"); Logger.Instance.LogMessage(TracingLevel.ERROR, $"Unexpected Error in EventHandler:\n {ex}");