How to get key character using Virtual Key without using Native code?

Viewed 258

I have need to get key character value from Virtual Key while type in TextBox. Currently we are using below code but it is not working in Release Mode

Platform : UWP

/// <summary>
/// Represents the KeyCode for keydown.
/// </summary>
internal class KeyCode
{
    /// <summary>
    /// Helps to get the UniCode based on input keys.
    /// </summary>
    /// <param name="key">input key.</param>
    /// <returns>Unicode.</returns>
    internal static string KeyCodeToUnicode(VirtualKey key)
    {
        byte[] keyboardState = new byte[255];
        bool keyboardStateStatus = GetKeyboardState(keyboardState);



        if (!keyboardStateStatus)
        {
            return string.Empty;
        }



        uint virtualKeyCode = (uint)key;
        uint scanCode = MapVirtualKey(virtualKeyCode, 0);
        IntPtr inputLocaleIdentifier = GetKeyboardLayout(0);



        StringBuilder result = new StringBuilder();
        int unicode = ToUnicodeEx(virtualKeyCode, scanCode, keyboardState, result, (int)5, 0, inputLocaleIdentifier);



        return result.ToString();
    }

    [DllImport("user32.dll", ExactSpelling = true)]
    private static extern bool GetKeyboardState(byte[] lpKeyState);



    [DllImport("user32.dll", ExactSpelling = true)]
    private static extern uint MapVirtualKey(uint uCode, uint uMapType);



    [DllImport("user32.dll", ExactSpelling = true)]
    private static extern IntPtr GetKeyboardLayout(uint idThread);



    [DllImport("user32.dll", ExactSpelling = true)]
    private static extern int ToUnicodeEx(uint wVirtKey, uint wScanCode, byte[] lpKeyState, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pwszBuff, int cchBuff, uint wFlags, IntPtr dwhkl);

}

Requirement: How to get key character while type in TextBox which needs work in both Release and Debug Mode.

1 Answers

How to get key character using Virtual Key without using Native code?

You have no need to get Unicode of key with Win32 extension method in UWP. VirtualKey is enum type in UWP platform. So you could use type conversion to convert it to ushort

 var unicode = (ushort)e.Key;

Update

I have need to get key character value from Virtual Key while type in TextBox. Currently we are using below code but it is not working in Release Mode

Please check the visual studio waring message. if you want to run above method in the release model. please add the user32.dll package to UWP project as native dll. Then it will work in release model.

enter image description here

Related