在.NET键盘映射键盘、NET

2023-09-03 01:12:31 作者:听一曲离殇、

如果我知道某个键已经pssed $ P $(如 Key.D3 ),并在切换键也,我怎么能找出字符引用(例如,#美国键盘,英国键盘英镑符号等)上?

If I know that a certain key has been pressed (eg Key.D3), and that the Shift key is also down (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift)), how can I find out what character that refers to (eg, # on US keyboard, UK pound sign on UK keyboard, etc)?

换句话说,我怎么能找到,编程,即移 + 3 生成#(它不会在非 - 美国键盘)。

Put another way, how can I find out, programatically, that Shift + 3 produces # (it wouldn't on a non-US keyboard).

推荐答案

如果你想确定是什么人物,你会得到一个给定的密钥给改性剂,你应该使用的 USER32 toascii将 功能。或者 ToAsciiEx 如果你想使用的键盘布局的等的那么当前的。

If you want to determine what character you will get from a given key with given modifiers, you should use the user32 ToAscii function. Or ToAsciiEx if you want to use a keyboard layout other then the current one.

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);
}

您现在可以使用这样的:

You can now use it like this:

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

如果你需要一个以上的修改,只是他们。 Keys.ShiftKey | Keys.AltKey

If you need more than one modifier, just or them. Keys.ShiftKey | Keys.AltKey