Question

I'm trying since 2 days to get the user's keyboard type (QWERTY or AZERTY) in C#. I thought about doing it with CultureInfo (localization), but that's definitely not a great workaround.

Any idea?

Was it helpful?

Solution

There's a GetKeyboardLayout method you can use;

 public class Program
   {
     const int KL_NAMELENGTH = 9;

     [DllImport("user32.dll")]
     private static extern long GetKeyboardLayoutName(
           System.Text.StringBuilder pwszKLID); 

     static void Main(string[] args)
     {
       StringBuilder name = new StringBuilder(KL_NAMELENGTH);

       GetKeyboardLayoutName(name);

       Console.WriteLine(name);

     }
   }

Source; Keyboard Type (Qwerty or Dvorak) detection

MSDN; http://msdn.microsoft.com/en-us/library/windows/desktop/ms646298(v=vs.85).aspx

OTHER TIPS

I know this is an old question but the chosen answer didn't exactly give me the info whether it's QWERTY or AZERTY. It will instead give you the Keyboard Identifier*

However, after fiddling around with virtual keys and DirectInput scancodes, this is what I came up with:

        public static class KeyboardLayoutUtils
        {
            [DllImport("user32.dll")]
            public static extern uint MapVirtualKey(uint uCode, uint uMapType);

            private static uint MAPVK_VSC_TO_VK = 0x01;

            // scan codes for US QWERTY based on DirectInput
            private static readonly uint[] _QwertyScanCodes =
            {
                0x00000010,
                0x00000011,
                0x00000012,
                0x00000013,
                0x00000014,
                0x00000015,
            };

            public static string GetCurrentKeyboardLayoutAsString()
            {
                // TODO: please add checks and validations, etc
                string layout = string.Empty;
                foreach (var code in _QwertyScanCodes)
                {
                    var vk = MapVirtualKey(code, MAPVK_VSC_TO_VK);
                    var val = KeyInterop.KeyFromVirtualKey((int) vk);
                    layout += val;
                }

                return layout;
            }
        }

So simply calling the above:

Console.WriteLine(KeyboardLayoutUtils.GetCurrentKeyboardLayoutAsString());
// outputs: QWERTY OR AZERTY depending on the active input language

Would give you "QWERTY" or "AZERTY" or actually the 6 characters on the qwerty positions.

*As an additional reference, although not exactly meant for C#, this page lists the Keyboard Identifiers: windows-language-pack-default-values

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top