c# - 如何在 WPF/C# 中捕获不同语言环境键盘上的 '#' 字符?

标签 c# wpf keypress

我的 WPF 应用程序处理键盘按下,特别是 # 和 * 字符,因为它是 VoIP 电话。

我在使用国际键盘时遇到了一个错误,尤其是英式英语键盘。通常我会监听 3 键,如果按下 shift 键修饰符,我们会触发一个事件来做一些事情。但是在英式键盘上,这是“£”字符。我发现英国英语键盘有一个专用的“#”键。显然,我们可以只听那个特定的键,但这并不能解决美式英语的情况,即 shift-3 和无数其他将它放在其他地方的键盘。

长话短说,我如何从按键中听到特定字符,无论是组合键还是单键,并对其使用react?

最佳答案

下面的函数 GetCharFromKey(Key key) 可以解决问题。

它使用一系列 win32 调用来解码按下的键:

  1. 获取 virtual key from WPF key

  2. 获取 scan code from the virtual key

  3. 获取 your unicode character

old post更详细地描述了它。

      public enum MapType : uint
      {
         MAPVK_VK_TO_VSC = 0x0,
         MAPVK_VSC_TO_VK = 0x1,
         MAPVK_VK_TO_CHAR = 0x2,
         MAPVK_VSC_TO_VK_EX = 0x3,
      }

      [DllImport("user32.dll")]
      public static extern int ToUnicode(
          uint wVirtKey,
          uint wScanCode,
          byte[] lpKeyState,
          [Out, MarshalAs(UnmanagedType.LPWStr, SizeParamIndex = 4)] 
            StringBuilder pwszBuff,
          int cchBuff,
          uint wFlags);

      [DllImport("user32.dll")]
      public static extern bool GetKeyboardState(byte[] lpKeyState);

      [DllImport("user32.dll")]
      public static extern uint MapVirtualKey(uint uCode, MapType uMapType);

      public static char GetCharFromKey(Key key)
      {
         char ch = ' ';

         int virtualKey = KeyInterop.VirtualKeyFromKey(key);
         byte[] keyboardState = new byte[256];
         GetKeyboardState(keyboardState);

         uint scanCode = MapVirtualKey((uint)virtualKey, MapType.MAPVK_VK_TO_VSC);
         StringBuilder stringBuilder = new StringBuilder(2);

         int result = ToUnicode((uint)virtualKey, scanCode, keyboardState, stringBuilder, stringBuilder.Capacity, 0);
         switch (result)
         {
            case -1: 
               break;
            case 0: 
               break;
            case 1:
               {
                  ch = stringBuilder[0];
                  break;
               }
            default:
               {
                  ch = stringBuilder[0];
                  break;
               }
         }
         return ch;
      }

关于c# - 如何在 WPF/C# 中捕获不同语言环境键盘上的 '#' 字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5825820/

相关文章:

c# - 如何禁止键盘输入文本框中的空格,空白,("_")字符

c# - 如何在加载数据时显示启动画面以消磨时间?

C# 应用程序未在启动时运行,Windows 10 上的启动影响 "not measured"

c# - 是否可以仅在加载所有模块后才显示 shell?

wpf - WCF RIA 的 EntityFramework 的 HasChanges

java - 如何使用 SWT AWT 处理 Windows 按键,最小化窗口并返回桌面

c# - Sitecore.Logging RollingFileAppender 缺失 [lockingModel]

c# - 搜索 24 小时内发生的 X 次事件

c# - 使用 WPF/MVVM Light Toolkit 处理窗口关闭事件

JavaScript `event.preventDefault()` 对于 Windows 中的 `alt+tab` 是无用的