【问题标题】:Keyboard Mapping in .NET.NET 中的键盘映射
【发布时间】:2010-10-18 05:27:21
【问题描述】:

如果我知道某个键已被按下(例如Key.D3),并且Shift 键也按下了(Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift)),我如何找出指的是哪个字符到(例如,美国键盘上的 #,英国键盘上的英国英镑符号等)?

换句话说,我如何以编程方式找出 Shift + 3 产生 # (它不会在非-美式键盘)。

【问题讨论】:

  • 用解决方案更新了我的答案,干杯。

标签: .net keyboard


【解决方案1】:

如果您想确定从给定键和给定修饰符中会得到什么字符,您应该使用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

【讨论】:

  • 是的,但是为什么呢? (不要回答)。我怎样才能以编程方式找出 Shift + Key.D3 产生 '#' (它不会在非美国键盘上)。
  • 哦,也许您应该完善您的问题以明确这一点。
  • 找到了解决办法,让我换个答案
  • 这看起来像个赢家!谢谢。
  • 好吧,我想它不是一个非常常用的功能,也不是 WinForms 团队优先考虑的问题。至少你可以随时 PInvoke Win32 代码。
猜你喜欢
  • 2012-07-12
  • 1970-01-01
  • 1970-01-01
  • 2014-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多