Sam

Sam

  • NA
  • 166
  • 0

Get ACTUAL keyboard layout for current windowl

Jul 15 2016 8:33 AM
Hi, 
 
For my multilingual application, I need to detect the change of current keyboard language.
 
I have my code (attached, simplified) that is called by a left mouse event delegate and works fine, except for one catch:
It will work for any language change as long as it is not after it was English.
In other words, while changing from any language to any other it will show the newly selected keyboard culture, after English it will still show English.
 
With another mouse press it will show the correct new language.
This will also happen if I change my computer default to any language: It will still behave differently after English, regardless of the computer language. 
 
I noticed that the language name on the taskbar is correct, but the program does not seem to get the same information. 
This indicates that the OS got it right, but not the program.
I have tried all kinds of workarounds, but for no avail (and ugly in any sense...)
(I remember seeing a post with the same problem in the past, but can not find it).
 
Does anyone know of a better (and consistent) way to get the current keyboard language?
Thanks,
Sam 
 
  1. using System.Globalization;
     
    [DllImport("user32.dll")]
    static extern IntPtr GetForegroundWindow();
    [DllImport("user32.dll")]
    static extern uint GetWindowThreadProcessId(IntPtr hwnd, IntPtr proccess);
    [DllImport("user32.dll")]
    static extern IntPtr GetKeyboardLayout(uint thread);
     
    static CultureInfo currentCulture;
    static CultureInfo newCulture;
     
    public static CultureInfo CheckIfCultureChanged()  //Called by left mouse event delegate
    {
    newCulture = GetNewCulture();
    if (newCulture.LCID != currentCulture.LCID)
    {
    currentCulture = newCulture;
    return newCulture;
    }
    else return currentCulture;
    }
    public static CultureInfo GetNewCulture()
    {
    IntPtr culturePtr = GetKeyboardLayout(GetWindowThreadProcessId(GetForegroundWindow(), IntPtr.Zero));
    CultureInfo newCulture = new CultureInfo((short)culturePtr.ToInt64());
    return newCulture;
    }