Keyboard mapping in .NET.

If I know that a certain key is pressed (for example, Key.D3) and that the key is Shiftalso unavailable ( Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift)), how can I find out which character it refers to (for example, #on the US keyboard, British pound on the British keyboard, etc.)?

In other words, how can I find out, programmatically, what Shift+ 3creates #(this would not be on a non-American keyboard).

+3
source share
1 answer

If you want to determine which character you will receive from a given key with the specified modifiers, you must use the function user32 ToAscii. Or ToAsciiEx, if you want to use a different keyboard layout than 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);
}

Now you can use it as follows:

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

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

+7
source

Source: https://habr.com/ru/post/1706090/


All Articles