@@ -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 IsForegroundWindow ( GetWindowHandle ( window ) ) ;
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,20 @@ 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+ // When application is exiting, the Application.Current will be null
368+ if ( Application . Current == null ) return ;
369+
370+ // Get the FL main window
371+ var hwnd = GetWindowHandle ( Application . Current . MainWindow , true ) ;
359372 if ( hwnd == HWND . Null ) return ;
360373
374+ // Check if the FL main window is the current foreground window
375+ if ( ! IsForegroundWindow ( hwnd ) )
376+ {
377+ var result = PInvoke . SetForegroundWindow ( hwnd ) ;
378+ if ( ! result ) throw new Win32Exception ( Marshal . GetLastWin32Error ( ) ) ;
379+ }
380+
361381 // Get the current foreground window thread ID
362382 var threadId = PInvoke . GetWindowThreadProcessId ( hwnd ) ;
363383 if ( threadId == 0 ) throw new Win32Exception ( Marshal . GetLastWin32Error ( ) ) ;
@@ -367,12 +387,10 @@ public static unsafe void SwitchToEnglishKeyboardLayout(bool backupPrevious)
367387 // the IME mode instead of switching to another layout.
368388 var currentLayout = PInvoke . GetKeyboardLayout ( threadId ) ;
369389 var currentLangId = ( uint ) currentLayout . Value & KeyboardLayoutLoWord ;
370- foreach ( var langTag in ImeLanguageTags )
390+ foreach ( var imeLangTag in ImeLanguageTags )
371391 {
372- if ( GetLanguageTag ( currentLangId ) . StartsWith ( langTag , StringComparison . OrdinalIgnoreCase ) )
373- {
374- return ;
375- }
392+ var langTag = GetLanguageTag ( currentLangId ) ;
393+ if ( langTag . StartsWith ( imeLangTag , StringComparison . OrdinalIgnoreCase ) ) return ;
376394 }
377395
378396 // Backup current keyboard layout
0 commit comments