UserActivityHook.cs 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837
  1. using System;
  2. using System.Runtime.InteropServices;
  3. using System.Reflection;
  4. using System.Threading;
  5. using System.Windows.Forms;
  6. using System.ComponentModel;
  7. namespace GeekDesk.Util
  8. {
  9. /// <summary>
  10. /// This class allows you to tap keyboard and mouse and / or to detect their activity even when an
  11. /// application runes in background or does not have any user interface at all. This class raises
  12. /// common .NET events with KeyEventArgs and MouseEventArgs so you can easily retrive any information you need.
  13. /// </summary>
  14. public class UserActivityHook
  15. {
  16. #region Windows structure definitions
  17. /// <summary>
  18. /// The POINT structure defines the x- and y- coordinates of a point.
  19. /// </summary>
  20. /// <remarks>
  21. /// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/gdi/rectangl_0tiq.asp
  22. /// </remarks>
  23. [StructLayout(LayoutKind.Sequential)]
  24. private class POINT
  25. {
  26. /// <summary>
  27. /// Specifies the x-coordinate of the point.
  28. /// </summary>
  29. public int x;
  30. /// <summary>
  31. /// Specifies the y-coordinate of the point.
  32. /// </summary>
  33. public int y;
  34. }
  35. /// <summary>
  36. /// The MOUSEHOOKSTRUCT structure contains information about a mouse event passed to a WH_MOUSE hook procedure, MouseProc.
  37. /// </summary>
  38. /// <remarks>
  39. /// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookstructures/cwpstruct.asp
  40. /// </remarks>
  41. [StructLayout(LayoutKind.Sequential)]
  42. private class MouseHookStruct
  43. {
  44. /// <summary>
  45. /// Specifies a POINT structure that contains the x- and y-coordinates of the cursor, in screen coordinates.
  46. /// </summary>
  47. public POINT pt;
  48. /// <summary>
  49. /// Handle to the window that will receive the mouse message corresponding to the mouse event.
  50. /// </summary>
  51. public int hwnd;
  52. /// <summary>
  53. /// Specifies the hit-test value. For a list of hit-test values, see the description of the WM_NCHITTEST message.
  54. /// </summary>
  55. public int wHitTestCode;
  56. /// <summary>
  57. /// Specifies extra information associated with the message.
  58. /// </summary>
  59. public int dwExtraInfo;
  60. }
  61. /// <summary>
  62. /// The MSLLHOOKSTRUCT structure contains information about a low-level keyboard input event.
  63. /// </summary>
  64. [StructLayout(LayoutKind.Sequential)]
  65. private class MouseLLHookStruct
  66. {
  67. /// <summary>
  68. /// Specifies a POINT structure that contains the x- and y-coordinates of the cursor, in screen coordinates.
  69. /// </summary>
  70. public POINT pt;
  71. /// <summary>
  72. /// If the message is WM_MOUSEWHEEL, the high-order word of this member is the wheel delta.
  73. /// The low-order word is reserved. A positive value indicates that the wheel was rotated forward,
  74. /// away from the user; a negative value indicates that the wheel was rotated backward, toward the user.
  75. /// One wheel click is defined as WHEEL_DELTA, which is 120.
  76. ///If the message is WM_XBUTTONDOWN, WM_XBUTTONUP, WM_XBUTTONDBLCLK, WM_NCXBUTTONDOWN, WM_NCXBUTTONUP,
  77. /// or WM_NCXBUTTONDBLCLK, the high-order word specifies which X button was pressed or released,
  78. /// and the low-order word is reserved. This value can be one or more of the following values. Otherwise, mouseData is not used.
  79. ///XBUTTON1
  80. ///The first X button was pressed or released.
  81. ///XBUTTON2
  82. ///The second X button was pressed or released.
  83. /// </summary>
  84. public int mouseData;
  85. /// <summary>
  86. /// Specifies the event-injected flag. An application can use the following value to test the mouse flags. Value Purpose
  87. ///LLMHF_INJECTED Test the event-injected flag.
  88. ///0
  89. ///Specifies whether the event was injected. The value is 1 if the event was injected; otherwise, it is 0.
  90. ///1-15
  91. ///Reserved.
  92. /// </summary>
  93. public int flags;
  94. /// <summary>
  95. /// Specifies the time stamp for this message.
  96. /// </summary>
  97. public int time;
  98. /// <summary>
  99. /// Specifies extra information associated with the message.
  100. /// </summary>
  101. public int dwExtraInfo;
  102. }
  103. /// <summary>
  104. /// The KBDLLHOOKSTRUCT structure contains information about a low-level keyboard input event.
  105. /// </summary>
  106. /// <remarks>
  107. /// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookstructures/cwpstruct.asp
  108. /// </remarks>
  109. [StructLayout(LayoutKind.Sequential)]
  110. private class KeyboardHookStruct
  111. {
  112. /// <summary>
  113. /// Specifies a virtual-key code. The code must be a value in the range 1 to 254.
  114. /// </summary>
  115. public int vkCode;
  116. /// <summary>
  117. /// Specifies a hardware scan code for the key.
  118. /// </summary>
  119. public int scanCode;
  120. /// <summary>
  121. /// Specifies the extended-key flag, event-injected flag, context code, and transition-state flag.
  122. /// </summary>
  123. public int flags;
  124. /// <summary>
  125. /// Specifies the time stamp for this message.
  126. /// </summary>
  127. public int time;
  128. /// <summary>
  129. /// Specifies extra information associated with the message.
  130. /// </summary>
  131. public int dwExtraInfo;
  132. }
  133. #endregion
  134. #region Windows function imports
  135. /// <summary>
  136. /// The SetWindowsHookEx function installs an application-defined hook procedure into a hook chain.
  137. /// You would install a hook procedure to monitor the system for certain types of events. These events
  138. /// are associated either with a specific thread or with all threads in the same desktop as the calling thread.
  139. /// </summary>
  140. /// <param name="idHook">
  141. /// [in] Specifies the type of hook procedure to be installed. This parameter can be one of the following values.
  142. /// </param>
  143. /// <param name="lpfn">
  144. /// [in] Pointer to the hook procedure. If the dwThreadId parameter is zero or specifies the identifier of a
  145. /// thread created by a different process, the lpfn parameter must point to a hook procedure in a dynamic-link
  146. /// library (DLL). Otherwise, lpfn can point to a hook procedure in the code associated with the current process.
  147. /// </param>
  148. /// <param name="hMod">
  149. /// [in] Handle to the DLL containing the hook procedure pointed to by the lpfn parameter.
  150. /// The hMod parameter must be set to NULL if the dwThreadId parameter specifies a thread created by
  151. /// the current process and if the hook procedure is within the code associated with the current process.
  152. /// </param>
  153. /// <param name="dwThreadId">
  154. /// [in] Specifies the identifier of the thread with which the hook procedure is to be associated.
  155. /// If this parameter is zero, the hook procedure is associated with all existing threads running in the
  156. /// same desktop as the calling thread.
  157. /// </param>
  158. /// <returns>
  159. /// If the function succeeds, the return value is the handle to the hook procedure.
  160. /// If the function fails, the return value is NULL. To get extended error information, call GetLastError.
  161. /// </returns>
  162. /// <remarks>
  163. /// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookfunctions/setwindowshookex.asp
  164. /// </remarks>
  165. [DllImport("user32.dll", CharSet = CharSet.Auto,
  166. CallingConvention = CallingConvention.StdCall, SetLastError = true)]
  167. private static extern int SetWindowsHookEx(
  168. int idHook,
  169. HookProc lpfn,
  170. IntPtr hMod,
  171. int dwThreadId);
  172. /// <summary>
  173. /// The UnhookWindowsHookEx function removes a hook procedure installed in a hook chain by the SetWindowsHookEx function.
  174. /// </summary>
  175. /// <param name="idHook">
  176. /// [in] Handle to the hook to be removed. This parameter is a hook handle obtained by a previous call to SetWindowsHookEx.
  177. /// </param>
  178. /// <returns>
  179. /// If the function succeeds, the return value is nonzero.
  180. /// If the function fails, the return value is zero. To get extended error information, call GetLastError.
  181. /// </returns>
  182. /// <remarks>
  183. /// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookfunctions/setwindowshookex.asp
  184. /// </remarks>
  185. [DllImport("user32.dll", CharSet = CharSet.Auto,
  186. CallingConvention = CallingConvention.StdCall, SetLastError = true)]
  187. private static extern int UnhookWindowsHookEx(int idHook);
  188. /// <summary>
  189. /// The CallNextHookEx function passes the hook information to the next hook procedure in the current hook chain.
  190. /// A hook procedure can call this function either before or after processing the hook information.
  191. /// </summary>
  192. /// <param name="idHook">Ignored.</param>
  193. /// <param name="nCode">
  194. /// [in] Specifies the hook code passed to the current hook procedure.
  195. /// The next hook procedure uses this code to determine how to process the hook information.
  196. /// </param>
  197. /// <param name="wParam">
  198. /// [in] Specifies the wParam value passed to the current hook procedure.
  199. /// The meaning of this parameter depends on the type of hook associated with the current hook chain.
  200. /// </param>
  201. /// <param name="lParam">
  202. /// [in] Specifies the lParam value passed to the current hook procedure.
  203. /// The meaning of this parameter depends on the type of hook associated with the current hook chain.
  204. /// </param>
  205. /// <returns>
  206. /// This value is returned by the next hook procedure in the chain.
  207. /// The current hook procedure must also return this value. The meaning of the return value depends on the hook type.
  208. /// For more information, see the descriptions of the individual hook procedures.
  209. /// </returns>
  210. /// <remarks>
  211. /// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookfunctions/setwindowshookex.asp
  212. /// </remarks>
  213. [DllImport("user32.dll", CharSet = CharSet.Auto,
  214. CallingConvention = CallingConvention.StdCall)]
  215. private static extern int CallNextHookEx(
  216. int idHook,
  217. int nCode,
  218. int wParam,
  219. IntPtr lParam);
  220. /// <summary>
  221. /// The CallWndProc hook procedure is an application-defined or library-defined callback
  222. /// function used with the SetWindowsHookEx function. The HOOKPROC type defines a pointer
  223. /// to this callback function. CallWndProc is a placeholder for the application-defined
  224. /// or library-defined function name.
  225. /// </summary>
  226. /// <param name="nCode">
  227. /// [in] Specifies whether the hook procedure must process the message.
  228. /// If nCode is HC_ACTION, the hook procedure must process the message.
  229. /// If nCode is less than zero, the hook procedure must pass the message to the
  230. /// CallNextHookEx function without further processing and must return the
  231. /// value returned by CallNextHookEx.
  232. /// </param>
  233. /// <param name="wParam">
  234. /// [in] Specifies whether the message was sent by the current thread.
  235. /// If the message was sent by the current thread, it is nonzero; otherwise, it is zero.
  236. /// </param>
  237. /// <param name="lParam">
  238. /// [in] Pointer to a CWPSTRUCT structure that contains details about the message.
  239. /// </param>
  240. /// <returns>
  241. /// If nCode is less than zero, the hook procedure must return the value returned by CallNextHookEx.
  242. /// If nCode is greater than or equal to zero, it is highly recommended that you call CallNextHookEx
  243. /// and return the value it returns; otherwise, other applications that have installed WH_CALLWNDPROC
  244. /// hooks will not receive hook notifications and may behave incorrectly as a result. If the hook
  245. /// procedure does not call CallNextHookEx, the return value should be zero.
  246. /// </returns>
  247. /// <remarks>
  248. /// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookfunctions/callwndproc.asp
  249. /// </remarks>
  250. private delegate int HookProc(int nCode, int wParam, IntPtr lParam);
  251. /// <summary>
  252. /// The ToAscii function translates the specified virtual-key code and keyboard
  253. /// state to the corresponding character or characters. The function translates the code
  254. /// using the input language and physical keyboard layout identified by the keyboard layout handle.
  255. /// </summary>
  256. /// <param name="uVirtKey">
  257. /// [in] Specifies the virtual-key code to be translated.
  258. /// </param>
  259. /// <param name="uScanCode">
  260. /// [in] Specifies the hardware scan code of the key to be translated.
  261. /// The high-order bit of this value is set if the key is up (not pressed).
  262. /// </param>
  263. /// <param name="lpbKeyState">
  264. /// [in] Pointer to a 256-byte array that contains the current keyboard state.
  265. /// Each element (byte) in the array contains the state of one key.
  266. /// If the high-order bit of a byte is set, the key is down (pressed).
  267. /// The low bit, if set, indicates that the key is toggled on. In this function,
  268. /// only the toggle bit of the CAPS LOCK key is relevant. The toggle state
  269. /// of the NUM LOCK and SCROLL LOCK keys is ignored.
  270. /// </param>
  271. /// <param name="lpwTransKey">
  272. /// [out] Pointer to the buffer that receives the translated character or characters.
  273. /// </param>
  274. /// <param name="fuState">
  275. /// [in] Specifies whether a menu is active. This parameter must be 1 if a menu is active, or 0 otherwise.
  276. /// </param>
  277. /// <returns>
  278. /// If the specified key is a dead key, the return value is negative. Otherwise, it is one of the following values.
  279. /// Value Meaning
  280. /// 0 The specified virtual key has no translation for the current state of the keyboard.
  281. /// 1 One character was copied to the buffer.
  282. /// 2 Two characters were copied to the buffer. This usually happens when a dead-key character
  283. /// (accent or diacritic) stored in the keyboard layout cannot be composed with the specified
  284. /// virtual key to form a single character.
  285. /// </returns>
  286. /// <remarks>
  287. /// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/userinput/keyboardinput/keyboardinputreference/keyboardinputfunctions/toascii.asp
  288. /// </remarks>
  289. [DllImport("user32")]
  290. private static extern int ToAscii(
  291. int uVirtKey,
  292. int uScanCode,
  293. byte[] lpbKeyState,
  294. byte[] lpwTransKey,
  295. int fuState);
  296. /// <summary>
  297. /// The GetKeyboardState function copies the status of the 256 virtual keys to the
  298. /// specified buffer.
  299. /// </summary>
  300. /// <param name="pbKeyState">
  301. /// [in] Pointer to a 256-byte array that contains keyboard key states.
  302. /// </param>
  303. /// <returns>
  304. /// If the function succeeds, the return value is nonzero.
  305. /// If the function fails, the return value is zero. To get extended error information, call GetLastError.
  306. /// </returns>
  307. /// <remarks>
  308. /// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/userinput/keyboardinput/keyboardinputreference/keyboardinputfunctions/toascii.asp
  309. /// </remarks>
  310. [DllImport("user32")]
  311. private static extern int GetKeyboardState(byte[] pbKeyState);
  312. [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
  313. private static extern short GetKeyState(int vKey);
  314. #endregion
  315. #region Windows constants
  316. //values from Winuser.h in Microsoft SDK.
  317. /// <summary>
  318. /// Windows NT/2000/XP: Installs a hook procedure that monitors low-level mouse input events.
  319. /// </summary>
  320. private const int WH_MOUSE_LL = 14;
  321. /// <summary>
  322. /// Windows NT/2000/XP: Installs a hook procedure that monitors low-level keyboard input events.
  323. /// </summary>
  324. private const int WH_KEYBOARD_LL = 13;
  325. /// <summary>
  326. /// Installs a hook procedure that monitors mouse messages. For more information, see the MouseProc hook procedure.
  327. /// </summary>
  328. private const int WH_MOUSE = 7;
  329. /// <summary>
  330. /// Installs a hook procedure that monitors keystroke messages. For more information, see the KeyboardProc hook procedure.
  331. /// </summary>
  332. private const int WH_KEYBOARD = 2;
  333. /// <summary>
  334. /// The WM_MOUSEMOVE message is posted to a window when the cursor moves.
  335. /// </summary>
  336. private const int WM_MOUSEMOVE = 0x200;
  337. /// <summary>
  338. /// The WM_LBUTTONDOWN message is posted when the user presses the left mouse button
  339. /// </summary>
  340. private const int WM_LBUTTONDOWN = 0x201;
  341. /// <summary>
  342. /// The WM_RBUTTONDOWN message is posted when the user presses the right mouse button
  343. /// </summary>
  344. private const int WM_RBUTTONDOWN = 0x204;
  345. /// <summary>
  346. /// The WM_MBUTTONDOWN message is posted when the user presses the middle mouse button
  347. /// </summary>
  348. private const int WM_MBUTTONDOWN = 0x207;
  349. /// <summary>
  350. /// The WM_LBUTTONUP message is posted when the user releases the left mouse button
  351. /// </summary>
  352. private const int WM_LBUTTONUP = 0x202;
  353. /// <summary>
  354. /// The WM_RBUTTONUP message is posted when the user releases the right mouse button
  355. /// </summary>
  356. private const int WM_RBUTTONUP = 0x205;
  357. /// <summary>
  358. /// The WM_MBUTTONUP message is posted when the user releases the middle mouse button
  359. /// </summary>
  360. private const int WM_MBUTTONUP = 0x208;
  361. /// <summary>
  362. /// The WM_LBUTTONDBLCLK message is posted when the user double-clicks the left mouse button
  363. /// </summary>
  364. private const int WM_LBUTTONDBLCLK = 0x203;
  365. /// <summary>
  366. /// The WM_RBUTTONDBLCLK message is posted when the user double-clicks the right mouse button
  367. /// </summary>
  368. private const int WM_RBUTTONDBLCLK = 0x206;
  369. /// <summary>
  370. /// The WM_RBUTTONDOWN message is posted when the user presses the right mouse button
  371. /// </summary>
  372. private const int WM_MBUTTONDBLCLK = 0x209;
  373. /// <summary>
  374. /// The WM_MOUSEWHEEL message is posted when the user presses the mouse wheel.
  375. /// </summary>
  376. private const int WM_MOUSEWHEEL = 0x020A;
  377. /// <summary>
  378. /// The WM_KEYDOWN message is posted to the window with the keyboard focus when a nonsystem
  379. /// key is pressed. A nonsystem key is a key that is pressed when the ALT key is not pressed.
  380. /// </summary>
  381. private const int WM_KEYDOWN = 0x100;
  382. /// <summary>
  383. /// The WM_KEYUP message is posted to the window with the keyboard focus when a nonsystem
  384. /// key is released. A nonsystem key is a key that is pressed when the ALT key is not pressed,
  385. /// or a keyboard key that is pressed when a window has the keyboard focus.
  386. /// </summary>
  387. private const int WM_KEYUP = 0x101;
  388. /// <summary>
  389. /// The WM_SYSKEYDOWN message is posted to the window with the keyboard focus when the user
  390. /// presses the F10 key (which activates the menu bar) or holds down the ALT key and then
  391. /// presses another key. It also occurs when no window currently has the keyboard focus;
  392. /// in this case, the WM_SYSKEYDOWN message is sent to the active window. The window that
  393. /// receives the message can distinguish between these two contexts by checking the context
  394. /// code in the lParam parameter.
  395. /// </summary>
  396. private const int WM_SYSKEYDOWN = 0x104;
  397. /// <summary>
  398. /// The WM_SYSKEYUP message is posted to the window with the keyboard focus when the user
  399. /// releases a key that was pressed while the ALT key was held down. It also occurs when no
  400. /// window currently has the keyboard focus; in this case, the WM_SYSKEYUP message is sent
  401. /// to the active window. The window that receives the message can distinguish between
  402. /// these two contexts by checking the context code in the lParam parameter.
  403. /// </summary>
  404. private const int WM_SYSKEYUP = 0x105;
  405. private const byte VK_SHIFT = 0x10;
  406. private const byte VK_CAPITAL = 0x14;
  407. private const byte VK_NUMLOCK = 0x90;
  408. #endregion
  409. /// <summary>
  410. /// Creates an instance of UserActivityHook object and sets mouse and keyboard hooks.
  411. /// </summary>
  412. /// <exception cref="Win32Exception">Any windows problem.</exception>
  413. public UserActivityHook()
  414. {
  415. Start();
  416. }
  417. /// <summary>
  418. /// Creates an instance of UserActivityHook object and installs both or one of mouse and/or keyboard hooks and starts rasing events
  419. /// </summary>
  420. /// <param name="InstallMouseHook"><b>true</b> if mouse events must be monitored</param>
  421. /// <param name="InstallKeyboardHook"><b>true</b> if keyboard events must be monitored</param>
  422. /// <exception cref="Win32Exception">Any windows problem.</exception>
  423. /// <remarks>
  424. /// To create an instance without installing hooks call new UserActivityHook(false, false)
  425. /// </remarks>
  426. public UserActivityHook(bool InstallMouseHook, bool InstallKeyboardHook)
  427. {
  428. Start(InstallMouseHook, InstallKeyboardHook);
  429. }
  430. /// <summary>
  431. /// Destruction.
  432. /// </summary>
  433. ~UserActivityHook()
  434. {
  435. //uninstall hooks and do not throw exceptions
  436. Stop(true, true, false);
  437. }
  438. /// <summary>
  439. /// Occurs when the user moves the mouse, presses any mouse button or scrolls the wheel
  440. /// </summary>
  441. ///
  442. public bool EnableMouse = false;
  443. public event MouseEventHandler OnMouseLeftDown;
  444. public event MouseEventHandler OnMouseLeftUp;
  445. public event MouseEventHandler OnMouseWheelDown;
  446. public event MouseEventHandler OnMouseWheelUp;
  447. public bool MouseLeftDownEnable()
  448. {
  449. return OnMouseLeftDown != null;
  450. }
  451. public bool MouseLeftUpEnable()
  452. {
  453. return OnMouseLeftUp != null;
  454. }
  455. public bool MouseWheelDownEnable()
  456. {
  457. return OnMouseWheelDown != null;
  458. }
  459. public bool MouseWheelUpEnable()
  460. {
  461. return OnMouseWheelUp != null;
  462. }
  463. /// <summary>
  464. /// Occurs when the user presses a key
  465. /// </summary>
  466. public event KeyEventHandler KeyDown;
  467. /// <summary>
  468. /// Occurs when the user presses and releases
  469. /// </summary>
  470. public event KeyPressEventHandler KeyPress;
  471. /// <summary>
  472. /// Occurs when the user releases a key
  473. /// </summary>
  474. public event KeyEventHandler KeyUp;
  475. /// <summary>
  476. /// Stores the handle to the mouse hook procedure.
  477. /// </summary>
  478. private int hMouseHook = 0;
  479. /// <summary>
  480. /// Stores the handle to the keyboard hook procedure.
  481. /// </summary>
  482. private int hKeyboardHook = 0;
  483. /// <summary>
  484. /// Declare MouseHookProcedure as HookProc type.
  485. /// </summary>
  486. private static HookProc MouseHookProcedure;
  487. /// <summary>
  488. /// Declare KeyboardHookProcedure as HookProc type.
  489. /// </summary>
  490. private static HookProc KeyboardHookProcedure;
  491. /// <summary>
  492. /// Installs both mouse and keyboard hooks and starts rasing events
  493. /// </summary>
  494. /// <exception cref="Win32Exception">Any windows problem.</exception>
  495. public void Start()
  496. {
  497. this.Start(true, true);
  498. }
  499. /// <summary>
  500. /// Installs both or one of mouse and/or keyboard hooks and starts rasing events
  501. /// </summary>
  502. /// <param name="InstallMouseHook"><b>true</b> if mouse events must be monitored</param>
  503. /// <param name="InstallKeyboardHook"><b>true</b> if keyboard events must be monitored</param>
  504. /// <exception cref="Win32Exception">Any windows problem.</exception>
  505. public void Start(bool InstallMouseHook, bool InstallKeyboardHook)
  506. {
  507. this.EnableMouse = InstallMouseHook;
  508. // install Mouse hook only if it is not installed and must be installed
  509. if (hMouseHook == 0 && EnableMouse)
  510. {
  511. // Create an instance of HookProc.
  512. MouseHookProcedure = new HookProc(MouseHookProc);
  513. //install hook
  514. hMouseHook = SetWindowsHookEx(
  515. WH_MOUSE_LL,
  516. MouseHookProcedure,
  517. Marshal.GetHINSTANCE(
  518. Assembly.GetExecutingAssembly().GetModules()[0]),
  519. 0);
  520. //If SetWindowsHookEx fails.
  521. if (hMouseHook == 0)
  522. {
  523. //Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set.
  524. int errorCode = Marshal.GetLastWin32Error();
  525. //do cleanup
  526. Stop(true, false, false);
  527. //Initializes and throws a new instance of the Win32Exception class with the specified error.
  528. throw new Win32Exception(errorCode);
  529. }
  530. }
  531. // install Keyboard hook only if it is not installed and must be installed
  532. if (hKeyboardHook == 0 && InstallKeyboardHook)
  533. {
  534. // Create an instance of HookProc.
  535. KeyboardHookProcedure = new HookProc(KeyboardHookProc);
  536. //install hook
  537. hKeyboardHook = SetWindowsHookEx(
  538. WH_KEYBOARD_LL,
  539. KeyboardHookProcedure,
  540. Marshal.GetHINSTANCE(
  541. Assembly.GetExecutingAssembly().GetModules()[0]),
  542. 0);
  543. //If SetWindowsHookEx fails.
  544. if (hKeyboardHook == 0)
  545. {
  546. //Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set.
  547. int errorCode = Marshal.GetLastWin32Error();
  548. //do cleanup
  549. Stop(false, true, false);
  550. //Initializes and throws a new instance of the Win32Exception class with the specified error.
  551. throw new Win32Exception(errorCode);
  552. }
  553. }
  554. }
  555. /// <summary>
  556. /// Stops monitoring both mouse and keyboard events and rasing events.
  557. /// </summary>
  558. /// <exception cref="Win32Exception">Any windows problem.</exception>
  559. public void Stop()
  560. {
  561. this.Stop(true, true, true);
  562. }
  563. /// <summary>
  564. /// Stops monitoring both or one of mouse and/or keyboard events and rasing events.
  565. /// </summary>
  566. /// <param name="UninstallMouseHook"><b>true</b> if mouse hook must be uninstalled</param>
  567. /// <param name="UninstallKeyboardHook"><b>true</b> if keyboard hook must be uninstalled</param>
  568. /// <param name="ThrowExceptions"><b>true</b> if exceptions which occured during uninstalling must be thrown</param>
  569. /// <exception cref="Win32Exception">Any windows problem.</exception>
  570. public void Stop(bool UninstallMouseHook, bool UninstallKeyboardHook, bool ThrowExceptions)
  571. {
  572. //if mouse hook set and must be uninstalled
  573. if (hMouseHook != 0 && UninstallMouseHook)
  574. {
  575. //uninstall hook
  576. int retMouse = UnhookWindowsHookEx(hMouseHook);
  577. //reset invalid handle
  578. hMouseHook = 0;
  579. //if failed and exception must be thrown
  580. if (retMouse == 0 && ThrowExceptions)
  581. {
  582. //Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set.
  583. int errorCode = Marshal.GetLastWin32Error();
  584. //Initializes and throws a new instance of the Win32Exception class with the specified error.
  585. throw new Win32Exception(errorCode);
  586. }
  587. }
  588. //if keyboard hook set and must be uninstalled
  589. if (hKeyboardHook != 0 && UninstallKeyboardHook)
  590. {
  591. //uninstall hook
  592. int retKeyboard = UnhookWindowsHookEx(hKeyboardHook);
  593. //reset invalid handle
  594. hKeyboardHook = 0;
  595. //if failed and exception must be thrown
  596. if (retKeyboard == 0 && ThrowExceptions)
  597. {
  598. //Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set.
  599. int errorCode = Marshal.GetLastWin32Error();
  600. //Initializes and throws a new instance of the Win32Exception class with the specified error.
  601. throw new Win32Exception(errorCode);
  602. }
  603. }
  604. }
  605. /// <summary>
  606. /// A callback function which will be called every time a mouse activity detected.
  607. /// </summary>
  608. /// <param name="nCode">
  609. /// [in] Specifies whether the hook procedure must process the message.
  610. /// If nCode is HC_ACTION, the hook procedure must process the message.
  611. /// If nCode is less than zero, the hook procedure must pass the message to the
  612. /// CallNextHookEx function without further processing and must return the
  613. /// value returned by CallNextHookEx.
  614. /// </param>
  615. /// <param name="wParam">
  616. /// [in] Specifies whether the message was sent by the current thread.
  617. /// If the message was sent by the current thread, it is nonzero; otherwise, it is zero.
  618. /// </param>
  619. /// <param name="lParam">
  620. /// [in] Pointer to a CWPSTRUCT structure that contains details about the message.
  621. /// </param>
  622. /// <returns>
  623. /// If nCode is less than zero, the hook procedure must return the value returned by CallNextHookEx.
  624. /// If nCode is greater than or equal to zero, it is highly recommended that you call CallNextHookEx
  625. /// and return the value it returns; otherwise, other applications that have installed WH_CALLWNDPROC
  626. /// hooks will not receive hook notifications and may behave incorrectly as a result. If the hook
  627. /// procedure does not call CallNextHookEx, the return value should be zero.
  628. /// </returns>
  629. private int MouseHookProc(int nCode, int wParam, IntPtr lParam)
  630. {
  631. // if ok and someone listens to our events
  632. if ((nCode >= 0) && EnableMouse)
  633. {
  634. //Marshall the data from callback.
  635. MouseLLHookStruct mouseHookStruct = (MouseLLHookStruct)Marshal.PtrToStructure(lParam, typeof(MouseLLHookStruct));
  636. //detect button clicked
  637. MouseButtons button = MouseButtons.None;
  638. short mouseDelta = 0;
  639. switch (wParam)
  640. {
  641. case WM_LBUTTONDOWN:
  642. case WM_LBUTTONUP:
  643. button = MouseButtons.Left;
  644. break;
  645. case WM_RBUTTONDOWN:
  646. case WM_RBUTTONUP:
  647. //case WM_RBUTTONUP:
  648. //case WM_RBUTTONDBLCLK:
  649. button = MouseButtons.Right;
  650. break;
  651. case WM_MOUSEWHEEL:
  652. case WM_MBUTTONDOWN:
  653. case WM_MBUTTONUP:
  654. button = MouseButtons.Middle;
  655. //If the message is WM_MOUSEWHEEL, the high-order word of mouseData member is the wheel delta.
  656. //One wheel click is defined as WHEEL_DELTA, which is 120.
  657. //(value >> 16) & 0xffff; retrieves the high-order word from the given 32-bit value
  658. mouseDelta = (short)((mouseHookStruct.mouseData >> 16) & 0xffff);
  659. //TODO: X BUTTONS (I havent them so was unable to test)
  660. //If the message is WM_XBUTTONDOWN, WM_XBUTTONUP, WM_XBUTTONDBLCLK, WM_NCXBUTTONDOWN, WM_NCXBUTTONUP,
  661. //or WM_NCXBUTTONDBLCLK, the high-order word specifies which X button was pressed or released,
  662. //and the low-order word is reserved. This value can be one or more of the following values.
  663. //Otherwise, mouseData is not used.
  664. break;
  665. }
  666. //double clicks
  667. int clickCount = 0;
  668. if (button != MouseButtons.None)
  669. if (wParam == WM_LBUTTONDBLCLK || wParam == WM_RBUTTONDBLCLK) clickCount = 2;
  670. else clickCount = 1;
  671. //generate event
  672. MouseEventArgs e = new MouseEventArgs(
  673. button,
  674. clickCount,
  675. mouseHookStruct.pt.x,
  676. mouseHookStruct.pt.y,
  677. mouseDelta);
  678. //raise it
  679. switch (wParam)
  680. {
  681. case WM_LBUTTONDOWN:
  682. this.OnMouseLeftDown?.Invoke(this, e);
  683. break;
  684. case WM_LBUTTONUP:
  685. this.OnMouseLeftUp?.Invoke(this, e);
  686. break;
  687. case WM_RBUTTONDOWN:
  688. break;
  689. case WM_RBUTTONUP:
  690. break;
  691. case WM_MOUSEWHEEL:
  692. break;
  693. case WM_MBUTTONDOWN:
  694. this.OnMouseWheelDown?.Invoke(this, e);
  695. break;
  696. case WM_MBUTTONUP:
  697. this.OnMouseWheelUp?.Invoke(this, e);
  698. break;
  699. }
  700. }
  701. //call next hook
  702. return CallNextHookEx(hMouseHook, nCode, wParam, lParam);
  703. }
  704. /// <summary>
  705. /// A callback function which will be called every time a keyboard activity detected.
  706. /// </summary>
  707. /// <param name="nCode">
  708. /// [in] Specifies whether the hook procedure must process the message.
  709. /// If nCode is HC_ACTION, the hook procedure must process the message.
  710. /// If nCode is less than zero, the hook procedure must pass the message to the
  711. /// CallNextHookEx function without further processing and must return the
  712. /// value returned by CallNextHookEx.
  713. /// </param>
  714. /// <param name="wParam">
  715. /// [in] Specifies whether the message was sent by the current thread.
  716. /// If the message was sent by the current thread, it is nonzero; otherwise, it is zero.
  717. /// </param>
  718. /// <param name="lParam">
  719. /// [in] Pointer to a CWPSTRUCT structure that contains details about the message.
  720. /// </param>
  721. /// <returns>
  722. /// If nCode is less than zero, the hook procedure must return the value returned by CallNextHookEx.
  723. /// If nCode is greater than or equal to zero, it is highly recommended that you call CallNextHookEx
  724. /// and return the value it returns; otherwise, other applications that have installed WH_CALLWNDPROC
  725. /// hooks will not receive hook notifications and may behave incorrectly as a result. If the hook
  726. /// procedure does not call CallNextHookEx, the return value should be zero.
  727. /// </returns>
  728. private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam)
  729. {
  730. //indicates if any of underlaing events set e.Handled flag
  731. bool handled = false;
  732. //it was ok and someone listens to events
  733. if ((nCode >= 0) && (KeyDown != null || KeyUp != null || KeyPress != null))
  734. {
  735. //read structure KeyboardHookStruct at lParam
  736. KeyboardHookStruct MyKeyboardHookStruct = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct));
  737. //raise KeyDown
  738. if (KeyDown != null && (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN))
  739. {
  740. Keys keyData = (Keys)MyKeyboardHookStruct.vkCode;
  741. KeyEventArgs e = new KeyEventArgs(keyData);
  742. KeyDown(this, e);
  743. handled = handled || e.Handled;
  744. }
  745. // raise KeyPress
  746. if (KeyPress != null && wParam == WM_KEYDOWN)
  747. {
  748. bool isDownShift = ((GetKeyState(VK_SHIFT) & 0x80) == 0x80 ? true : false);
  749. bool isDownCapslock = (GetKeyState(VK_CAPITAL) != 0 ? true : false);
  750. byte[] keyState = new byte[256];
  751. GetKeyboardState(keyState);
  752. byte[] inBuffer = new byte[2];
  753. if (ToAscii(MyKeyboardHookStruct.vkCode,
  754. MyKeyboardHookStruct.scanCode,
  755. keyState,
  756. inBuffer,
  757. MyKeyboardHookStruct.flags) == 1)
  758. {
  759. char key = (char)inBuffer[0];
  760. if ((isDownCapslock ^ isDownShift) && Char.IsLetter(key)) key = Char.ToUpper(key);
  761. KeyPressEventArgs e = new KeyPressEventArgs(key);
  762. KeyPress(this, e);
  763. handled = handled || e.Handled;
  764. }
  765. }
  766. // raise KeyUp
  767. if (KeyUp != null && (wParam == WM_KEYUP || wParam == WM_SYSKEYUP))
  768. {
  769. Keys keyData = (Keys)MyKeyboardHookStruct.vkCode;
  770. KeyEventArgs e = new KeyEventArgs(keyData);
  771. KeyUp(this, e);
  772. handled = handled || e.Handled;
  773. }
  774. }
  775. //if event handled in application do not handoff to other listeners
  776. if (handled)
  777. return 1;
  778. else
  779. return CallNextHookEx(hKeyboardHook, nCode, wParam, lParam);
  780. }
  781. }
  782. }