1

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 virtual keys beforehand perhaps?) Is there any way to accomplish this?

user
  • 16,429
  • 28
  • 80
  • 97
  • @Tigran, http://en.wikipedia.org/wiki/Scancode – user Sep 24 '11 at 08:17
  • KeyPress is too late, you'll need to record it at KeyDown. KeyEventArgs however doesn't expose it, requiring overriding WndProc to catch the WM_KEYDOWN message. – Hans Passant Sep 24 '11 at 16:33

2 Answers2

0

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

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.

Community
  • 1
  • 1
Rich Tebb
  • 6,806
  • 2
  • 23
  • 25