版博士V2.0程序
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 

325 строки
13 KiB

  1. using MaiMuControl.Device;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.Linq;
  6. using System.Runtime.InteropServices;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. namespace MaiMuAOI.KeyboardHookProc
  10. {
  11. public class KeyboardTools
  12. {
  13. #region WIN32API
  14. //private const int WM_KEYDOWN = 0x100;//KEYDOWN       
  15. //private const int WM_KEYUP = 0x101;//KEYUP       
  16. //private const int WM_SYSKEYDOWN = 0x104;//SYSKEYDOWN       
  17. //private const int WM_SYSKEYUP = 0x105;//SYSKEYUP
  18. //private static int HookProc(int nCode, Int32 wParam, IntPtr lParam);
  19. private int hKeyboardHook = 0;//声明键盘钩子处理的初始值
  20. private ScanerCodes codes = new ScanerCodes();//13为键盘钩子
  21. //定义成静态,这样不会抛出回收异常
  22. private static HookProc hookproc;
  23. delegate int HookProc(int nCode, Int32 wParam, IntPtr lParam);
  24. [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]     //设置钩子
  25. private static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);
  26. [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]     //卸载钩子
  27. private static extern bool UnhookWindowsHookEx(int idHook);
  28. [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] //继续下个钩子
  29. private static extern int CallNextHookEx(int idHook, int nCode, Int32 wParam, IntPtr lParam);
  30. [DllImport("user32", EntryPoint = "GetKeyNameText")]
  31. private static extern int GetKeyNameText(int IParam, StringBuilder lpBuffer, int nSize);
  32. [DllImport("user32", EntryPoint = "GetKeyboardState")]     //获取按键的状态
  33. private static extern int GetKeyboardState(byte[] pbKeyState);
  34. [DllImport("user32", EntryPoint = "ToAscii")]     //ToAscii职能的转换指定的虚拟键码和键盘状态的相应字符或字符
  35. private static extern bool ToAscii(int VirtualKey, int ScanCode, byte[] lpKeySate, ref uint lpChar, int uFlags);
  36. //int VirtualKey //[in] 指定虚拟关键代码进行翻译。      
  37. //int uScanCode, // [in] 指定的硬件扫描码的关键须翻译成英文。高阶位的这个值设定的关键,如果是(不压)      
  38. //byte[] lpbKeyState, // [in] 指针,以256字节数组,包含当前键盘的状态。每个元素(字节)的数组包含状态的一个关键。如果高阶位的字节是一套,关键是下跌(按下)。在低比特,如/果设置表明,关键是对切换。在此功能,只有肘位的CAPS LOCK键是相关的。在切换状态的NUM个锁和滚动锁定键被忽略。      //byte[] lpwTransKey, // [out] 指针的缓冲区收到翻译字符或字符。      //uint fuState); // [in] Specifies whether a menu is active. This parameter must be 1 if a menu is active, or 0 otherwise.
  39. [DllImport("kernel32.dll")]     //使用WINDOWS API函数代替获取当前实例的函数,防止钩子失效
  40. private static extern IntPtr GetModuleHandle(string name);
  41. #endregion
  42. public Action<WarningEnum, string> WarningEvent;
  43. //public Action<ScanerCodes> ScanerEvent;
  44. public Action<string> ScanerEvent;
  45. public KeyboardTools()
  46. {
  47. }
  48. /// <summary>
  49. /// 处理回调时需锁定
  50. /// </summary>
  51. public bool isLock { get; set; }
  52. public bool start()
  53. {
  54. try
  55. {
  56. if (hKeyboardHook == 0)
  57. {
  58. hookproc = new HookProc(KeyboardHookProc);
  59. //GetModuleHandle 函数 替代 Marshal.GetHINSTANCE
  60. //防止在 framework4.0中 注册钩子不成功
  61. IntPtr modulePtr = GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName);
  62. //WH_KEYBOARD_LL=13
  63. //全局钩子 WH_KEYBOARD_LL
  64. // hKeyboardHook = SetWindowsHookEx(13, hookproc, Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]), 0);
  65. hKeyboardHook = SetWindowsHookEx(13, hookproc, modulePtr, 0);
  66. }
  67. return (hKeyboardHook != 0);
  68. }
  69. catch (Exception ex)
  70. {
  71. WarningEvent?.Invoke(WarningEnum.Normal, ex.Message);
  72. return false;
  73. }
  74. }
  75. public bool stop()
  76. {
  77. try
  78. {
  79. if (hKeyboardHook != 0)
  80. {
  81. bool retKeyboard = UnhookWindowsHookEx(hKeyboardHook);
  82. hookproc = null;
  83. hKeyboardHook = 0;
  84. return retKeyboard;
  85. }
  86. return true;
  87. }
  88. catch
  89. {
  90. return false;
  91. }
  92. }
  93. private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam)
  94. {
  95. try
  96. {
  97. EventMsg msg = (EventMsg)Marshal.PtrToStructure(lParam, typeof(EventMsg));
  98. codes.Add(msg);
  99. if (msg.message == 13 && msg.paramH > 0 && !string.IsNullOrWhiteSpace(codes.Result))
  100. {
  101. ScanerEvent?.Invoke(codes.Result);
  102. }
  103. return CallNextHookEx(hKeyboardHook, nCode, wParam, lParam);
  104. }
  105. catch (Exception ex)
  106. {
  107. return 0;
  108. }
  109. }
  110. public void Dispose()
  111. {
  112. stop();
  113. }
  114. public class ScanerCodes
  115. {
  116. private int ts = 100; // 指定输入间隔为300毫秒以内时为连续输入
  117. private List<List<EventMsg>> _keys = new List<List<EventMsg>>();
  118. private List<int> _keydown = new List<int>(); // 保存组合键状态
  119. private List<string> _result = new List<string>(); // 返回结果集
  120. private DateTime _last = DateTime.Now;
  121. private byte[] _state = new byte[256];
  122. private string _key = string.Empty;
  123. private string _cur = string.Empty;
  124. public EventMsg Event
  125. {
  126. get
  127. {
  128. if (_keys.Count == 0)
  129. {
  130. return new EventMsg();
  131. }
  132. else
  133. {
  134. return _keys[_keys.Count - 1][_keys[_keys.Count - 1].Count - 1];
  135. }
  136. }
  137. }
  138. public List<int> KeyDowns
  139. {
  140. get
  141. {
  142. return _keydown;
  143. }
  144. }
  145. public DateTime LastInput
  146. {
  147. get
  148. {
  149. return _last;
  150. }
  151. }
  152. public byte[] KeyboardState
  153. {
  154. get
  155. {
  156. return _state;
  157. }
  158. }
  159. public int KeyDownCount
  160. {
  161. get
  162. {
  163. return _keydown.Count;
  164. }
  165. }
  166. public string Result
  167. {
  168. get
  169. {
  170. if (_result.Count > 0)
  171. {
  172. return _result[_result.Count - 1].Trim();
  173. }
  174. else
  175. {
  176. return null;
  177. }
  178. }
  179. }
  180. public string CurrentKey
  181. {
  182. get
  183. {
  184. return _key;
  185. }
  186. }
  187. public string CurrentChar
  188. {
  189. get
  190. {
  191. return _cur;
  192. }
  193. }
  194. public bool isShift
  195. {
  196. get
  197. {
  198. return _keydown.Contains(160);
  199. }
  200. }
  201. public void Add(EventMsg msg)
  202. {
  203. #region 记录按键信息
  204. // 首次按下按键
  205. if (_keys.Count == 0)
  206. {
  207. _keys.Add(new List<EventMsg>());
  208. _keys[0].Add(msg);
  209. _result.Add(string.Empty);
  210. }
  211. // 未释放其他按键时按下按键
  212. else if (_keydown.Count > 0)
  213. {
  214. _keys[_keys.Count - 1].Add(msg);
  215. }
  216. // 单位时间内按下按键
  217. else if (((TimeSpan)(DateTime.Now - _last)).TotalMilliseconds < ts)
  218. {
  219. _keys[_keys.Count - 1].Add(msg);
  220. }
  221. // 从新记录输入内容
  222. else
  223. {
  224. _keys.Add(new List<EventMsg>());
  225. _keys[_keys.Count - 1].Add(msg);
  226. _result.Add(string.Empty);
  227. }
  228. #endregion
  229. _last = DateTime.Now;
  230. #region 获取键盘状态
  231. // 记录正在按下的按键
  232. if (msg.paramH == 0 && !_keydown.Contains(msg.message))
  233. {
  234. _keydown.Add(msg.message);
  235. }
  236. // 清除已松开的按键
  237. if (msg.paramH > 0 && _keydown.Contains(msg.message))
  238. {
  239. _keydown.Remove(msg.message);
  240. }
  241. #endregion
  242. #region 计算按键信息
  243. int v = msg.message & 0xff;
  244. int c = msg.paramL & 0xff;
  245. StringBuilder strKeyName = new StringBuilder(500);
  246. if (GetKeyNameText(c * 65536, strKeyName, 255) > 0)
  247. {
  248. _key = strKeyName.ToString().Trim(new char[] { ' ', '\0' });
  249. GetKeyboardState(_state);
  250. if (_key.Length == 1 && msg.paramH == 0)// && msg.paramH == 0
  251. {
  252. // 根据键盘状态和shift缓存判断输出字符
  253. _cur = ShiftChar(_key, isShift, _state).ToString();
  254. _result[_result.Count - 1] += _cur;
  255. }
  256. //判断是+ 强制添加+
  257. else if (_key.Length == 5 && msg.paramH == 0 && msg.paramL == 78 && msg.message == 107)
  258. {
  259. // 根据键盘状态和shift缓存判断输出字符
  260. _cur = Convert.ToChar('+').ToString();
  261. _result[_result.Count - 1] += _cur;
  262. }
  263. // 备选          
  264. else
  265. {
  266. _cur = string.Empty;
  267. }
  268. }
  269. #endregion
  270. }
  271. private char ShiftChar(string k, bool isShiftDown, byte[] state)
  272. {
  273. bool capslock = state[0x14] == 1;
  274. bool numlock = state[0x90] == 1;
  275. bool scrolllock = state[0x91] == 1;
  276. bool shiftdown = state[0xa0] == 1;
  277. char chr = (capslock ? k.ToUpper() : k.ToLower()).ToCharArray()[0];
  278. if (isShiftDown)
  279. {
  280. if (chr >= 'a' && chr <= 'z')
  281. {
  282. chr = (char)((int)chr - 32);
  283. }
  284. else if (chr >= 'A' && chr <= 'Z')
  285. {
  286. if (chr == 'Z')
  287. {
  288. string s = "";
  289. }
  290. chr = (char)((int)chr + 32);
  291. }
  292. else
  293. {
  294. string s = "`1234567890-=[];',./";
  295. string u = "~!@#$%^&*()_+{}:\"<>?";
  296. if (s.IndexOf(chr) >= 0)
  297. {
  298. return (u.ToCharArray())[s.IndexOf(chr)];
  299. }
  300. }
  301. }
  302. return chr;
  303. }
  304. }
  305. public struct EventMsg
  306. {
  307. public int message;
  308. public int paramL;
  309. public int paramH;
  310. public int Time;
  311. public int hwnd;
  312. }
  313. }
  314. }