Determining which keyboard is sending keystrokes

后端 未结 5 877
梦如初夏
梦如初夏 2021-01-22 12:04

I have 2 keyboards hooked up to my machine (one on PS/2, the other on USB). How would I determine which keyboard is sending the keystrokes in C#?

5条回答
  •  余生分开走
    2021-01-22 12:26

    Ok, here's a really kludgy method that would only work with a very limited subset of use cases:

    1. Tape, glue down, or short out a set of modifier keys (Right Ctrl, for example) on one of the keyboards.
    2. On each key press, look at the modifiers. If the modifiers are set as they would be on the glued-down keyboard, assume that keyboard is the source. If not, assume it's the other keyboard.

    Limitations:

    1. You can't use the glued keyboard outside your app, since only it knows to ignore the modifier keys.
    2. You can't use those modifier keys within your own app as part of keyboard shortcuts.
    3. The other keyboard can impersonate yours (accidentally or not) if the user holds down the correct buttons.
    4. You'll need to disable StickyKeys.
    5. Using Alt or Ctrl has a down side: if you press the other one, Windows may have a use for that combination that your app won't catch.

    Unknown #1: whether ModifierKeys is only populated from the keyboard that was the source of the key click, or comes from the sum of all modifiers across all connected keyboards. I suspect each keyboard internally sends the modifiers attached to the keystroke and that Windows doesn't aggregate them.

    Unknown #2: whether or not System.Windows.Forms.Control.ModifierKeys provides only Ctrl/Shift/Alt bits, or provides enough detail to, say, distinguish the Right Ctrl key from the left. Here are the keys you could theoretically test for, I don't know how many are provided via ModifierKeys:

    http://msdn.microsoft.com/en-us/library/system.windows.forms.keys.aspx

提交回复
热议问题