【问题标题】:Intercept keyboard input using current keyboard layout使用当前键盘布局拦截键盘输入
【发布时间】:2015-02-11 01:13:50
【问题描述】:

我已经使用 SetWindowsHookEx() 函数实现了一个低级键盘挂钩。它工作正常并为每次击键返回一个虚拟键码。我可以使用 KeyInterop.KeyFromVirtualKey() 将此虚拟键代码转换为 System.Windows.Input.Key。但目标是在当前键盘布局中得到一个与这个虚拟键码对应的符号。

即对于德语布局,我想为 Key.Z 获取“Y”,为 Key.Y 获取“Z”。

有人可以帮忙吗?

谢谢。

【问题讨论】:

    标签: c# keyboard hook


    【解决方案1】:

    调用 GetKeyboardLayout 来检索活动布局值,然后,做一些条件循环来获得你想要的结果。

    【讨论】:

      【解决方案2】:

      你应该看看这些方法GetKeyboardStateGetKeyboardLayoutMapVirtualKeyExToUnicodeEx

      解决方案应该类似于

      byte[] keyboardState = new byte[256];
      GetKeyboardState(keyboardState);
      IntPtr handle = GetKeyboardLayout(0);
      uint scanCode = MapVirtualKeyEx(VirtualKeyCode, 0, handle);
      StringBuilder stringBuilder = new StringBuilder(2);
      
      int nResultLower = ToUnicodeEx(VirtualKeyCode, scanCode, keyboardState, stringBuilder,
                                             stringBuilder.Capacity, 0, handle);
      
      string output= string.Empty;
      if (nResultLower != 0)
      {
        output = stringBuilder.ToString();
      }
      

      【讨论】:

        【解决方案3】:

        不太确定我们是否在谈论相同的场景,但我最近遇到了类似的问题,即 ToUnicodeEx 中断了用户的击键(当使用诸如“alt+numpad”之类的修饰符或在德语键盘上使用“+”键修饰符时),导致如果需要,则将意外的字母打印到屏幕上。

        通过在运行 ToUnicodeEx 之前将 @Nejchy 的代码与 ClearKeyboardBuffer 方法相结合解决了我的问题:

        private static bool ClearKeyboardBuffer(uint vk, uint sc, IntPtr hkl)
        {
            StringBuilder sb = new StringBuilder(10);
            int rc = -1;
            bool isDeadKey = false;
            while (rc < 0)
            {
                rc = user32.ToUnicodeEx(vk, sc, new byte[256], sb, sb.Capacity, 0, hkl);
                if (!isDeadKey && rc == -1) isDeadKey = true;
                Console.Write(rc);
            }
            return isDeadKey;
        }
        

        在执行“ToUnicodeEx”的代码中:

        var isDeadKey = ClearKeyboardBuffer((uint)aKey, 0, hKd);
        if (isDeadKey) return;
        user32.ToUnicodeEx((uint)aKey, vkCode, keyboardState, characters, 10, (uint)0, hKd);
        

        参考: http://www.siao2.com/2006/03/23/558658.aspx http://www.siao2.com/2006/04/06/569632.aspx

        再看他的代码: https://stackoverflow.com/a/8705696/802848

        【讨论】:

          猜你喜欢
          • 2016-12-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多