zoukankan      html  css  js  c++  java
  • WPF中 键盘输入事件OnPreviewKeyDown中没有e.KeyChar()的解决方法

    不知道为啥C#有这个方法而WPF没有,在需要获取输入字符的情景下,虽然可以用e.key.toString()去获得字母,但是想获取小键盘的数字或者字符的时候就不会返回正确的结果。

    贴上一个别人写的方法,本质上是调用的winform的dll。新建cs复制粘贴即可使用。

    using System.Runtime.InteropServices;
    using System.Text;
    using System.Windows.Input;
    
    namespace ClassicPassWd
    {
        public class GetCharFromKey
        {
            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 KeyChars(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;
            }
        }
    }
    

      

  • 相关阅读:
    NOI2007项链工厂——sbTreap代码
    终于还是卡着进队了
    SCOI RP+=INF
    每日算法——新型在线LCA
    每日算法——并查集的应用
    每日算法--矩阵乘法优化递推
    神一般的数据结构--可持久化treap
    算法竞赛中的数论经典定理
    Baby Step Gaint Step
    素数分组 哥德巴赫猜想
  • 原文地址:https://www.cnblogs.com/KangYh/p/12902124.html
Copyright © 2011-2022 走看看