diff --git a/DD2Switcher/Program.cs b/DD2Switcher/Program.cs index 2b0f2ee..758817e 100644 --- a/DD2Switcher/Program.cs +++ b/DD2Switcher/Program.cs @@ -217,17 +217,19 @@ namespace DD2Switcher { Console.WriteLine($"Event detected in state: {CurrentState}, transitioning to WAITING_TO_ADVANCE"); CurrentState = SequenceState.WAITING_TO_ADVANCE; Console.WriteLine($"State changed to: {CurrentState}"); + HandleWaitingToAdvance(); } private static void HandleWaitingToAdvance() { // Start timer to advance after N milliseconds Console.WriteLine($"Starting 500ms timer in WAITING_TO_ADVANCE state"); - System.Threading.Thread.Sleep(500); - if (CurrentState == SequenceState.WAITING_TO_ADVANCE) { - CurrentState = SequenceState.ADVANCE; - Console.WriteLine($"Timer expired, transitioning to ADVANCE state"); - HandleSequenceEvent(); - } + Task.Delay(500).ContinueWith(_ => { + if (CurrentState == SequenceState.WAITING_TO_ADVANCE) { + CurrentState = SequenceState.ADVANCE; + Console.WriteLine($"Timer expired, transitioning to ADVANCE state"); + HandleSequenceEvent(); + } + }); } private static void HandleAdvance() { @@ -270,9 +272,20 @@ namespace DD2Switcher { [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr hWnd); + [DllImport("user32.dll")] + private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); + + [DllImport("user32.dll")] + private static extern bool BringWindowToTop(IntPtr hWnd); + + [DllImport("user32.dll")] + private static extern IntPtr SetActiveWindow(IntPtr hWnd); + [DllImport("user32.dll")] private static extern short GetKeyState(int nVirtKey); + private const int SW_RESTORE = 9; + [DllImport("kernel32.dll", SetLastError = true)] [return:MarshalAs(UnmanagedType.Bool)] static extern bool AllocConsole(); @@ -541,21 +554,10 @@ namespace DD2Switcher { PushHistory(ActiveIndex); Console.WriteLine($"Setting foreground window to: {window.ProcessName} PID:{window.Id}"); - bool result = SetForegroundWindow(window.MainWindowHandle); - Console.WriteLine($"SetForegroundWindow result: {result}"); - - // Force window to front with additional methods - if (result) { - // Bring window to front and activate it - SetForegroundWindow(window.MainWindowHandle); - System.Threading.Thread.Sleep(50); // Small delay - - // Check if it actually worked - var currentForeground = GetForegroundWindow(); - bool actuallySwitched = (currentForeground == window.MainWindowHandle); - Console.WriteLine( - $"Actually switched: {actuallySwitched} (Current: {currentForeground}, Target: {window.MainWindowHandle})"); - } + SetForegroundWindow(window.MainWindowHandle); + ShowWindow(window.MainWindowHandle, SW_RESTORE); + BringWindowToTop(window.MainWindowHandle); + SetActiveWindow(window.MainWindowHandle); ActiveIndex = index; AdjustAffinities();