@@ -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 GetWindowHandle ( window ) . Equals ( PInvoke . GetForegroundWindow ( ) ) ;
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,17 @@ 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
+ // Get the FL main window
368
+ var hwnd = GetWindowHandle ( Application . Current . MainWindow , true ) ;
359
369
if ( hwnd == HWND . Null ) return ;
360
370
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
+
361
378
// Get the current foreground window thread ID
362
379
var threadId = PInvoke . GetWindowThreadProcessId ( hwnd ) ;
363
380
if ( threadId == 0 ) throw new Win32Exception ( Marshal . GetLastWin32Error ( ) ) ;
@@ -367,12 +384,10 @@ public static unsafe void SwitchToEnglishKeyboardLayout(bool backupPrevious)
367
384
// the IME mode instead of switching to another layout.
368
385
var currentLayout = PInvoke . GetKeyboardLayout ( threadId ) ;
369
386
var currentLangId = ( uint ) currentLayout . Value & KeyboardLayoutLoWord ;
370
- foreach ( var langTag in ImeLanguageTags )
387
+ foreach ( var imeLangTag in ImeLanguageTags )
371
388
{
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 ;
376
391
}
377
392
378
393
// Backup current keyboard layout
0 commit comments