[分享]WPF 虚拟键盘
Posted 顺势而为
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[分享]WPF 虚拟键盘相关的知识,希望对你有一定的参考价值。
场景:用WPF做触屏的软件难免会需要用户输入的问题,至少是简单的数字,这个时候就免不了需要键盘输入。
思路:既然是虚拟键盘,那么我的目的就是模拟键盘输入即可。
1.模拟键盘输入
模拟键盘输入?那么肯定免不了调用Win32API了。所以查看下Win32API是否提供了键盘输入的功能,找到发送按键的函数:
[DllImport("user32.dll", EntryPoint = "PostMessageW")]
public static extern int PostMessage( int hwnd,int wMsg,int wParam,int lParam);
2.找到需要输入的控件:
[DllImport("user32.dll")] public static extern int GetFocus();
3.找到当前窗体
[DllImport("user32.dll")] public static extern int GetForegroundWindow(); [DllImport("user32.dll")] public static extern int AttachThreadInput(int idAttach,int idAttachTo,int fAttach); [DllImport("user32.dll")] public static extern int GetWindowThreadProcessId(int hwnd, int lpdwProcessId);
关键代码:
(1)Win32API功能类:
/// <summary> /// Win32接口功能类 /// </summary> public static class Win32API { /// <summary> /// 键入 /// </summary> public const int WM_KEYDOWN = 0x100; [DllImport("user32.dll", EntryPoint = "SendMessageW")] public static extern int SendMessage( int hwnd, int wMsg, int wParam, int lParam); [DllImport("user32.dll", EntryPoint = "PostMessageW")] public static extern int PostMessage( int hwnd, int wMsg, int wParam, int lParam); [DllImport("user32.dll")] public static extern int GetForegroundWindow(); [DllImport("user32.dll")] public static extern IntPtr GetLastActivePopup(IntPtr hWnd); [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr hWnd); [DllImport("user32.dll")] public static extern int GetFocus(); [DllImport("user32.dll")] public static extern int AttachThreadInput( int idAttach, int idAttachTo, int fAttach); [DllImport("user32.dll")] public static extern int GetWindowThreadProcessId( int hwnd, int lpdwProcessId); [DllImport("kernel32.dll")] public static extern int GetCurrentThreadId(); [DllImport("user32.dll")] public static extern IntPtr GetDesktopWindow(); }
(2)发送按键实现
/// <summary> /// 发送按键 /// </summary> /// <param name="asiiCode">键盘ascii码</param> private void SendKey(byte asiiCode) { AttachThreadInput(true); int getFocus = Win32API.GetFocus(); //向前台窗口发送按键消息 Win32API.PostMessage(getFocus, Win32API.WM_KEYDOWN, asiiCode, 0); AttachThreadInput(false); //取消线程亲和的关联 } /// <summary> /// 设置线程亲和,附到前台窗口所在线程,只有在线程内才可以获取线程内控件的焦点 /// </summary> /// <param name="b">是否亲和</param> private void AttachThreadInput(bool b) { Win32API.AttachThreadInput( Win32API.GetWindowThreadProcessId( Win32API.GetForegroundWindow(), 0), Win32API.GetCurrentThreadId(), Convert.ToInt32(b)); }
(3)附上按键ascii码表:
4.时间关系就做个简单的吧:
欢迎指正,转载请注明出处http://www.cnblogs.com/xinwang/p/6143169.html
以上是关于[分享]WPF 虚拟键盘的主要内容,如果未能解决你的问题,请参考以下文章
从 Windows 10 虚拟键盘输入到 WPF 文本框中的快乐表情符号未在文本框的 PreviewTextInput 事件中捕获