开发者

C# - Converting KeyPress to scancode/scancode to key name

开发者 https://www.devze.com 2023-04-06 22:55 出处:网络
I have a WinForm application where I need to capture a KeyPress and fetch the scancode for it.Along with that I need to convert existing scancodes int key names (by converting to vi开发者_运维问答rtua

I have a WinForm application where I need to capture a KeyPress and fetch the scancode for it. Along with that I need to convert existing scancodes int key names (by converting to vi开发者_运维问答rtual keys beforehand perhaps?) Is there any way to accomplish this?


The first part is possible, but tricky, because multiple Virtual Key (VK) codes will map to the same scancode (depending on the keyboard shift/ctrl/alt state).

I'm not sure what you mean by "key name," but if you're referring to the physical keyboard layout then, for your next step, you will need to make some assumptions about the key's location based on standard physical keyboard layouts (101-key, 102-key etc).

See my answer to this question for some sample code and a more detailed description.


If you still need it, you can use Reflection for private members access. I know it's not good idea and interfaces can change in next versions, but it works for .Net Framework 4.6

private void OnKeyDown(object sender, KeyEventArgs e)
{
    MSG l_Msg;
    ushort l_Scancode;
    PresentationSource source = e.InputSource;

    var l_MSGField = source.GetType().GetField("_lastKeyboardMessage", BindingFlags.NonPublic | BindingFlags.Instance);
    l_Msg = (MSG)l_MSGField.GetValue(source);
    l_Scancode = (ushort)(l_Msg.lParam.ToInt32() >> 16);

    //Use scancode
}
0

精彩评论

暂无评论...
验证码 换一张
取 消