星火微课系统客户端
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

KeyboardHookCommon.cs 10KB

1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
4 jaren geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. using System;
  2. using System.Runtime.InteropServices;
  3. using System.Windows.Forms;
  4. namespace Common.system
  5. {
  6. /// <summary>
  7. /// 键盘钩子
  8. /// 创建人:赵耀
  9. /// 创建时间:2020年9月11日
  10. /// </summary>
  11. public class KeyboardHookCommon
  12. {
  13. /// <summary>
  14. /// 全局按键按下
  15. /// </summary>
  16. public event KeyEventHandler KeyDownEvent;
  17. /// <summary>
  18. /// 窗口按键按下
  19. /// </summary>
  20. public event KeyPressEventHandler KeyPressEvent;
  21. /// <summary>
  22. /// 全局按键抬起
  23. /// </summary>
  24. public event KeyEventHandler KeyUpEvent;
  25. public delegate int HookProc(int nCode, int wParam, IntPtr lParam);
  26. private static int _hKeyboardHook; //声明键盘钩子处理的初始值
  27. //值在Microsoft SDK的Winuser.h里查询
  28. /// <summary>
  29. /// 线程键盘钩子监听鼠标消息设为2,全局键盘监听鼠标消息设为13
  30. /// </summary>
  31. public const int WH_KEYBOARD_LL = 13;
  32. /// <summary>
  33. /// 声明KeyboardHookProcedure作为HookProc类型
  34. /// </summary>
  35. private HookProc _keyboardHookProcedure;
  36. /// <summary>
  37. /// 自己创建窗口按键
  38. /// </summary>
  39. private const int WM_KEYDOWN = 0x100; //KEYDOWN
  40. /// <summary>
  41. /// 窗口按键抬起
  42. /// </summary>
  43. private const int WM_KEYUP = 0x101; //KEYUP
  44. /// <summary>
  45. /// 全局系统按键
  46. /// </summary>
  47. private const int WM_SYSKEYDOWN = 0x104; //SYSKEYDOWN
  48. /// <summary>
  49. /// 全局按键抬起
  50. /// </summary>
  51. private const int WM_SYSKEYUP = 0x105; //SYSKEYUP
  52. //键盘结构
  53. [StructLayout(LayoutKind.Sequential)]
  54. public class KeyboardHookStruct
  55. {
  56. public int vkCode; //定一个虚拟键码。该代码必须有一个价值的范围1至254
  57. public int scanCode; // 指定的硬件扫描码的关键
  58. public int flags; // 键标志
  59. public int time; // 指定的时间戳记的这个讯息
  60. public int dwExtraInfo; // 指定额外信息相关的信息
  61. }
  62. //使用此功能,安装了一个钩子
  63. [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
  64. public static extern int SetWindowsHookEx
  65. (
  66. int idHook,
  67. HookProc lpfn,
  68. IntPtr hInstance,
  69. int threadId
  70. );
  71. //调用此函数卸载钩子
  72. [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
  73. public static extern bool UnhookWindowsHookEx(int idHook);
  74. //使用此功能,通过信息钩子继续下一个钩子
  75. [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
  76. public static extern int CallNextHookEx
  77. (
  78. int idHook,
  79. int nCode,
  80. int wParam,
  81. IntPtr lParam
  82. );
  83. // 取得当前线程编号(线程钩子需要用到)
  84. [DllImport("kernel32.dll")]
  85. private static extern int GetCurrentThreadId();
  86. //使用WINDOWS API函数代替获取当前实例的函数,防止钩子失效
  87. [DllImport("kernel32.dll")]
  88. public static extern IntPtr GetModuleHandle(string name);
  89. //ToAscii职能的转换指定的虚拟键码和键盘状态的相应字符或字符
  90. [DllImport("user32")]
  91. public static extern int ToAscii
  92. (
  93. int uVirtKey, //[in] 指定虚拟关键代码进行翻译。
  94. int uScanCode, // [in] 指定的硬件扫描码的关键须翻译成英文。高阶位的这个值设定的关键,如果是(不压)
  95. byte[] lpbKeyState, // [in] 指针,以256字节数组,包含当前键盘的状态。每个元素(字节)的数组包含状态的一个关键。如果高阶位的字节是一套,关键是下跌(按下)。在低比特,如果设置表明,关键是对切换。在此功能,只有肘位的CAPS LOCK键是相关的。在切换状态的NUM个锁和滚动锁定键被忽略。
  96. byte[] lpwTransKey, // [out] 指针的缓冲区收到翻译字符或字符。
  97. int fuState
  98. ); // [in] Specifies whether a menu is active. This parameter must be 1 if a menu is active, or 0 otherwise.
  99. //获取按键的状态
  100. [DllImport("user32")]
  101. public static extern int GetKeyboardState(byte[] pbKeyState);
  102. [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
  103. private static extern short GetKeyState(int vKey);
  104. public void Start()
  105. {
  106. // 安装键盘钩子
  107. if (_hKeyboardHook == 0)
  108. {
  109. _keyboardHookProcedure = KeyboardHookProc;
  110. _hKeyboardHook = SetWindowsHookEx(
  111. WH_KEYBOARD_LL,
  112. _keyboardHookProcedure,
  113. GetModuleHandle(System.Diagnostics.Process.GetCurrentProcess().MainModule?.ModuleName),
  114. 0
  115. );
  116. //hKeyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardHookProcedure, Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]), 0);
  117. //************************************
  118. //键盘线程钩子
  119. //SetWindowsHookEx( 2,KeyboardHookProcedure, IntPtr.Zero, GetCurrentThreadId());//指定要监听的线程idGetCurrentThreadId(),
  120. //键盘全局钩子,需要引用空间(using System.Reflection;)
  121. //SetWindowsHookEx( 13,MouseHookProcedure,Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]),0);
  122. //
  123. //关于SetWindowsHookEx (int idHook, HookProc lpfn, IntPtr hInstance, int threadId)函数将钩子加入到钩子链表中,说明一下四个参数:
  124. //idHook 钩子类型,即确定钩子监听何种消息,上面的代码中设为2,即监听键盘消息并且是线程钩子,如果是全局钩子监听键盘消息应设为13,
  125. //线程钩子监听鼠标消息设为7,全局钩子监听鼠标消息设为14。lpfn 钩子子程的地址指针。如果dwThreadId参数为0 或是一个由别的进程创建的
  126. //线程的标识,lpfn必须指向DLL中的钩子子程。 除此以外,lpfn可以指向当前进程的一段钩子子程代码。钩子函数的入口地址,当钩子钩到任何
  127. //消息后便调用这个函数。hInstance应用程序实例的句柄。标识包含lpfn所指的子程的DLL。如果threadId 标识当前进程创建的一个线程,而且子
  128. //程代码位于当前进程,hInstance必须为NULL。可以很简单的设定其为本应用程序的实例句柄。threaded 与安装的钩子子程相关联的线程的标识符
  129. //如果为0,钩子子程与所有的线程关联,即为全局钩子
  130. //************************************
  131. //如果SetWindowsHookEx失败
  132. if (_hKeyboardHook == 0)
  133. {
  134. Stop();
  135. throw new Exception("安装键盘钩子失败");
  136. }
  137. }
  138. }
  139. public void Stop()
  140. {
  141. bool retKeyboard = true;
  142. if (_hKeyboardHook != 0)
  143. {
  144. retKeyboard = UnhookWindowsHookEx(_hKeyboardHook);
  145. _hKeyboardHook = 0;
  146. }
  147. try
  148. {
  149. if (!(retKeyboard))
  150. {
  151. throw new Exception("卸载钩子失败!");
  152. }
  153. }
  154. catch (Exception)
  155. {
  156. // ignored
  157. }
  158. }
  159. ////接收SetWindowsHookEx返回值
  160. //private static int _hHookValue = 0;
  161. private int KeyboardHookProc(int nCode, int wParam, IntPtr lParam)
  162. {
  163. // 侦听键盘事件
  164. if ((nCode >= 0) && (KeyDownEvent != null || KeyUpEvent != null || KeyPressEvent != null))
  165. {
  166. KeyboardHookStruct myKeyboardHookStruct = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct));
  167. // raise KeyDown
  168. if (KeyDownEvent != null && (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN))
  169. {
  170. Keys keyData = (Keys)myKeyboardHookStruct.vkCode;
  171. KeyEventArgs e = new KeyEventArgs(keyData);
  172. KeyDownEvent(this, e);
  173. }
  174. //键盘按下
  175. if (KeyPressEvent != null && wParam == WM_KEYDOWN)
  176. {
  177. byte[] keyState = new byte[256];
  178. GetKeyboardState(keyState);
  179. byte[] inBuffer = new byte[2];
  180. if (ToAscii(
  181. myKeyboardHookStruct.vkCode,
  182. myKeyboardHookStruct.scanCode,
  183. keyState,
  184. inBuffer,
  185. myKeyboardHookStruct.flags
  186. ) ==
  187. 1)
  188. {
  189. KeyPressEventArgs e = new KeyPressEventArgs((char)inBuffer[0]);
  190. KeyPressEvent(this, e);
  191. }
  192. }
  193. // 键盘抬起
  194. if (KeyUpEvent != null && (wParam == WM_KEYUP || wParam == WM_SYSKEYUP))
  195. {
  196. Keys keyData = (Keys)myKeyboardHookStruct.vkCode;
  197. KeyEventArgs e = new KeyEventArgs(keyData);
  198. KeyUpEvent(this, e);
  199. }
  200. }
  201. //如果返回1,则结束消息,这个消息到此为止,不再传递。
  202. //如果返回0或调用CallNextHookEx函数则消息出了这个钩子继续往下传递,也就是传给消息真正的接受者
  203. return CallNextHookEx(
  204. _hKeyboardHook,
  205. nCode,
  206. wParam,
  207. lParam
  208. );
  209. }
  210. ~KeyboardHookCommon()
  211. {
  212. Stop();
  213. }
  214. }
  215. }