Ejemplo n.º 1
0
        /// <summary>
        /// Get a unicode char from a key, according to current keyboard mappings
        /// See https://stackoverflow.com/questions/5825820/how-to-capture-the-character-on-different-locale-keyboards-in-wpf-c
        /// </summary>
        /// <param name="key">the key to convert</param>
        /// <returns>the converted char</returns>
        char GetCharFromKey(Keys key)
        {
            char ch = ' ';

            int virtualKey = (int)key;

            byte[] keyboardState = new byte[256];
            LowLevel.GetKeyboardState(keyboardState);

            uint          scanCode      = LowLevel.MapVirtualKey((uint)virtualKey, LowLevel.MapType.MAPVK_VK_TO_VSC);
            StringBuilder stringBuilder = new StringBuilder(2);

            int result = LowLevel.ToUnicode((uint)virtualKey, scanCode, keyboardState, stringBuilder, stringBuilder.Capacity, 0);

            if (stringBuilder.Length > 0)
            {
                switch (result)
                {
                case -1:
                    break;

                case 0:
                    break;

                case 1:
                {
                    ch = stringBuilder[0];
                    break;
                }

                default:
                {
                    ch = stringBuilder[0];
                    break;
                }
                }
            }
            return(ch);
        }