How do you get the character appropriate for the g

2019-02-26 02:34发布

How do you get the character appropriate for the given KeyDown event in WPF?

4条回答
混吃等死
2楼-- · 2019-02-26 03:13
 public enum MapType : uint
    {
        MAPVK_VK_TO_VSC = 0x0,
        MAPVK_VSC_TO_VK = 0x1,
        MAPVK_VK_TO_CHAR = 0x2,
        MAPVK_VSC_TO_VK_EX = 0x3,
    }
    [DllImport("user32.dll")]
    public static extern bool GetKeyboardState(byte[] lpKeyState);
    [DllImport("user32.dll")]
    public static extern uint MapVirtualKey(uint uCode, MapType uMapType);
    [DllImport("user32.dll")]
    public static extern int ToUnicode(
     uint wVirtKey,
     uint wScanCode,
     byte[] lpKeyState,
     [Out, MarshalAs(UnmanagedType.LPWStr, SizeParamIndex = 4)] 
        StringBuilder pwszBuff,
     int cchBuff,
     uint wFlags);

    public static char GetCharFromKey(Key key)
    {
        char ch = ' ';

        int virtualKey = KeyInterop.VirtualKeyFromKey(key);
        byte[] keyboardState = new byte[256];
        GetKeyboardState(keyboardState);

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

        int result = ToUnicode((uint)virtualKey, scanCode, keyboardState, stringBuilder, stringBuilder.Capacity, 0);
        switch (result)
        {
            case -1:
                break;
            case 0:
                break;
            case 1:
                {
                    ch = stringBuilder[0];
                    break;
                }
            default:
                {
                    ch = stringBuilder[0];
                    break;
                }
        }
        return ch;
    }
查看更多
Juvenile、少年°
3楼-- · 2019-02-26 03:20

Try this:

var virtualKey = (uint)KeyInterop.VirtualKeyFromKey(e.Key);
var keyCode = MapVirtualKey(virtualKey, 0);

Import function MapVirtualKey

[DllImport("user32.dll")]
static extern uint MapVirtualKey(uint uCode, uint uMapType);
查看更多
看我几分像从前
4楼-- · 2019-02-26 03:24

Not all KeyDown events correspond to a single, visible character -- for instance, Backspace and Enter. You will have to compare the event arg's contents with what you want to associate. For example, on my US QUERTY keyboard, the key at the top left is a back-tick, but it might look like something else to another keyboard.

查看更多
甜甜的少女心
5楼-- · 2019-02-26 03:32
private void UserControl1_KeyDown_1(object sender, KeyEventArgs e)
{   
    FieldInfo field = e.GetType().GetField
    (
       "_scanCode",
       BindingFlags.NonPublic |
       BindingFlags.Instance
    );

    Int32 scancode = (Int32)field.GetValue(e);

    char c = (char)scancode;
}
查看更多
登录 后发表回答