@@ -124,6 +124,16 @@ public static bool SetForegroundWindow(nint handle)
124
124
return PInvoke . SetForegroundWindow ( new ( handle ) ) ;
125
125
}
126
126
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
+
127
137
#endregion
128
138
129
139
#region Task Switching
@@ -354,10 +364,20 @@ public static unsafe void SwitchToEnglishKeyboardLayout(bool backupPrevious)
354
364
// No installed English layout found
355
365
if ( enHKL == HKL . Null ) return ;
356
366
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 ) ;
359
372
if ( hwnd == HWND . Null ) return ;
360
373
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
+
361
381
// Get the current foreground window thread ID
362
382
var threadId = PInvoke . GetWindowThreadProcessId ( hwnd ) ;
363
383
if ( threadId == 0 ) throw new Win32Exception ( Marshal . GetLastWin32Error ( ) ) ;
@@ -367,12 +387,10 @@ public static unsafe void SwitchToEnglishKeyboardLayout(bool backupPrevious)
367
387
// the IME mode instead of switching to another layout.
368
388
var currentLayout = PInvoke . GetKeyboardLayout ( threadId ) ;
369
389
var currentLangId = ( uint ) currentLayout . Value & KeyboardLayoutLoWord ;
370
- foreach ( var langTag in ImeLanguageTags )
390
+ foreach ( var imeLangTag in ImeLanguageTags )
371
391
{
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 ;
376
394
}
377
395
378
396
// Backup current keyboard layout
0 commit comments