@@ -124,6 +124,16 @@ public static bool SetForegroundWindow(nint handle)
124124 return PInvoke . SetForegroundWindow ( new ( handle ) ) ;
125125 }
126126
127+ public static bool IsForegroundWindow ( Window window )
128+ {
129+ return GetWindowHandle ( window ) . Equals ( PInvoke . GetForegroundWindow ( ) ) ;
130+ }
131+
132+ internal static bool IsForegroundWindow ( HWND handle )
133+ {
134+ return handle . Equals ( PInvoke . GetForegroundWindow ( ) ) ;
135+ }
136+
127137 #endregion
128138
129139 #region Task Switching
@@ -354,10 +364,17 @@ public static unsafe void SwitchToEnglishKeyboardLayout(bool backupPrevious)
354364 // No installed English layout found
355365 if ( enHKL == HKL . Null ) return ;
356366
357- // Get the current foreground window
358- var hwnd = PInvoke . GetForegroundWindow ( ) ;
367+ // Get the FL main window
368+ var hwnd = GetWindowHandle ( Application . Current . MainWindow , true ) ;
359369 if ( hwnd == HWND . Null ) return ;
360370
371+ // Check if the FL main window is the current foreground window
372+ if ( ! IsForegroundWindow ( hwnd ) )
373+ {
374+ var result = PInvoke . SetForegroundWindow ( hwnd ) ;
375+ if ( ! result ) throw new Win32Exception ( Marshal . GetLastWin32Error ( ) ) ;
376+ }
377+
361378 // Get the current foreground window thread ID
362379 var threadId = PInvoke . GetWindowThreadProcessId ( hwnd ) ;
363380 if ( threadId == 0 ) throw new Win32Exception ( Marshal . GetLastWin32Error ( ) ) ;
@@ -367,12 +384,10 @@ public static unsafe void SwitchToEnglishKeyboardLayout(bool backupPrevious)
367384 // the IME mode instead of switching to another layout.
368385 var currentLayout = PInvoke . GetKeyboardLayout ( threadId ) ;
369386 var currentLangId = ( uint ) currentLayout . Value & KeyboardLayoutLoWord ;
370- foreach ( var langTag in ImeLanguageTags )
387+ foreach ( var imeLangTag in ImeLanguageTags )
371388 {
372- if ( GetLanguageTag ( currentLangId ) . StartsWith ( langTag , StringComparison . OrdinalIgnoreCase ) )
373- {
374- return ;
375- }
389+ var langTag = GetLanguageTag ( currentLangId ) ;
390+ if ( langTag . StartsWith ( imeLangTag , StringComparison . OrdinalIgnoreCase ) ) return ;
376391 }
377392
378393 // Backup current keyboard layout
0 commit comments