.NET中的键盘映射

时间:2009-04-08 04:00:19

标签: .net keyboard

如果我知道某个键已按下(例如Key.D3),并且 Shift 键也已关闭(Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift)),我怎么能找到引用的是什么字符(例如,美国键盘上的,英国键盘上的英镑符号等)?

换句话说,我怎么能以编程方式找出 Shift + 3 产生(它不会在非-US键盘)。

1 个答案:

答案 0 :(得分:8)

如果要确定使用给定修饰符从给定键获得的字符,则应使用user32 ToAscii函数。或ToAsciiEx如果您想使用键盘布局其他,那么就是当前的。

using System.Runtime.InteropServices;
public static class User32Interop
{
  public static char ToAscii(Keys key, Keys modifiers)
  {
    var outputBuilder = new StringBuilder(2);
    int result = ToAscii((uint)key, 0, GetKeyState(modifiers),
                         outputBuilder, 0);
    if (result == 1)
      return outputBuilder[0];
    else
      throw new Exception("Invalid key");
  }

  private const byte HighBit = 0x80;
  private static byte[] GetKeyState(Keys modifiers)
  {
    var keyState = new byte[256];
    foreach (Keys key in Enum.GetValues(typeof(Keys)))
    {
      if ((modifiers & key) == key)
      {
        keyState[(int)key] = HighBit;
      }
    }
    return keyState;
  }

  [DllImport("user32.dll")]
  private static extern int ToAscii(uint uVirtKey, uint uScanCode,
                                    byte[] lpKeyState,
                                    [Out] StringBuilder lpChar,
                                    uint uFlags);
}

您现在可以像这样使用它:

char c = User32Interop.ToAscii(Keys.D3, Keys.ShiftKey); // = '#'

如果您需要多个修饰符,只需or个。 Keys.ShiftKey | Keys.AltKey