A piece of code:

[DllImport("user32.dll", SetLastError = true)] public static extern ushort GetKeyboardLayout([In] int idThread); [DllImport("user32.dll", SetLastError = true)] public static extern int GetWindowThreadProcessId([In] IntPtr hWnd,[Out, Optional] IntPtr lpdwProcessId); [DllImport("user32.dll", SetLastError = true)] public static extern IntPtr GetForegroundWindow(); public static string mss; static ushort GetKeyboardLayout() { return GetKeyboardLayout(GetWindowThreadProcessId(GetForegroundWindow(), IntPtr.Zero)); } 

Now when i try to get keyboard layout

 ushort lang = GetKeyboardLayout(); mss = lang.ToString(); TextBox1.Text = "Первоначальная раскладка: " + mss + "\n"; 

It does not show Rus or Eng but in figures such as 1049 etc.

How to fix it?

    1 answer 1

     using System.Globalization; 
     int id = GetKeyboardLayout(); CultureInfo ci = CultureInfo.GetCultureInfo(id); this.Text = id + " " + ci.ThreeLetterISOLanguageName + " " + ci.Name; 

    And there is still a lot of interesting things.


    Please note that you have the wrong P / Invoke signature! The GetKeyboardLayout function returns a handle, so the correct signature is:

     [DllImport("user32.dll")] static extern IntPtr GetKeyboardLayout(int idThread); 

    According to the documentation

    There is no trace of the keyboard.

    Therefore, we need to extract the lower word:

     static ushort GetKeyboardLayout() { return (ushort)GetKeyboardLayout(GetWindowThreadProcessId(GetForegroundWindow(), IntPtr.Zero)); } 
    • +1, but the P / Invoke-signature for the GetKeyboardLayout of the vehicle is incorrect => it is worth waiting for the crash. There in reality intptr. - VladD
    • And I get GetCultureInfo, if you do not trim the argument high bits ( id & 0xffff ). - VladD
    • @VladD, and how could you get something from ushort bits? o_O - Qwertiy
    • @VladD, hmm .. yes, there’s a sort of handle. But after all there is nothing to fall - it's just a register. - Qwertiy
    • Well, I get id = 0xfffffffff0c10419, for example. With such a value falls. - VladD