KeyboardListener.cs 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. using MediaBrowser.Common.Logging;
  2. using System;
  3. using System.Diagnostics;
  4. using System.Runtime.InteropServices;
  5. using System.Windows.Forms;
  6. namespace MediaBrowser.UI.UserInput
  7. {
  8. /// <summary>
  9. /// Provides a basic low-level keyboard listener
  10. /// Inspired by http://blogs.msdn.com/b/toub/archive/2006/05/03/589423.aspx
  11. /// Use the KeyDown event to listen for keys.
  12. /// Make sure to detach from the event when not needed.
  13. /// </summary>
  14. public static class KeyboardListener
  15. {
  16. #region KeyDown EventHandler
  17. /// <summary>
  18. /// The _ key down
  19. /// </summary>
  20. static volatile EventHandler<KeyEventArgs> _KeyDown;
  21. /// <summary>
  22. /// Fires whenever CurrentItem changes
  23. /// </summary>
  24. public static event EventHandler<KeyEventArgs> KeyDown
  25. {
  26. add
  27. {
  28. if (_KeyDown == null)
  29. {
  30. StartListening();
  31. }
  32. _KeyDown += value;
  33. }
  34. remove
  35. {
  36. _KeyDown -= value;
  37. if (_KeyDown == null && _hookID != IntPtr.Zero)
  38. {
  39. StopListening();
  40. }
  41. }
  42. }
  43. /// <summary>
  44. /// Raises the <see cref="E:KeyDown" /> event.
  45. /// </summary>
  46. /// <param name="e">The <see cref="KeyEventArgs" /> instance containing the event data.</param>
  47. private static void OnKeyDown(KeyEventArgs e)
  48. {
  49. e.SuppressKeyPress = false;
  50. if (_KeyDown != null)
  51. {
  52. // For now, don't async this
  53. // This will give listeners a chance to modify SuppressKeyPress if they want
  54. try
  55. {
  56. _KeyDown(null, e);
  57. }
  58. catch (Exception ex)
  59. {
  60. Logger.LogException("KeyDown event listener had an error: ", ex);
  61. }
  62. }
  63. }
  64. #endregion
  65. /// <summary>
  66. /// The W h_ KEYBOAR d_ LL
  67. /// </summary>
  68. private const int WH_KEYBOARD_LL = 13;
  69. /// <summary>
  70. /// The W m_ KEYDOWN
  71. /// </summary>
  72. private const int WM_KEYDOWN = 0x0100;
  73. /// <summary>
  74. /// The W m_ SYSKEYDOWN
  75. /// </summary>
  76. private const int WM_SYSKEYDOWN = 0x0104;
  77. /// <summary>
  78. /// The _hook ID
  79. /// </summary>
  80. private static IntPtr _hookID = IntPtr.Zero;
  81. /// <summary>
  82. /// The _proc
  83. /// </summary>
  84. private static LowLevelKeyboardProc _proc = HookCallback;
  85. /// <summary>
  86. /// Starts the listening.
  87. /// </summary>
  88. private static void StartListening()
  89. {
  90. Logger.LogInfo("Attaching low-level keyboard hook");
  91. _hookID = SetHook(_proc);
  92. }
  93. /// <summary>
  94. /// Stops the listening.
  95. /// </summary>
  96. private static void StopListening()
  97. {
  98. Logger.LogInfo("Detaching low-level keyboard hook");
  99. UnhookWindowsHookEx(_hookID);
  100. _hookID = IntPtr.Zero;
  101. }
  102. /// <summary>
  103. /// Sets the hook.
  104. /// </summary>
  105. /// <param name="proc">The proc.</param>
  106. /// <returns>IntPtr.</returns>
  107. private static IntPtr SetHook(LowLevelKeyboardProc proc)
  108. {
  109. using (var curProcess = Process.GetCurrentProcess())
  110. using (var curModule = curProcess.MainModule)
  111. {
  112. return SetWindowsHookEx(WH_KEYBOARD_LL, proc,
  113. GetModuleHandle(curModule.ModuleName), 0);
  114. }
  115. }
  116. /// <summary>
  117. /// Hooks the callback.
  118. /// </summary>
  119. /// <param name="nCode">The n code.</param>
  120. /// <param name="wParam">The w param.</param>
  121. /// <param name="lParam">The l param.</param>
  122. /// <returns>IntPtr.</returns>
  123. private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
  124. {
  125. var suppressKeyPress = false;
  126. if (nCode >= 0)
  127. {
  128. if (wParam == (IntPtr)WM_KEYDOWN || wParam == (IntPtr)WM_SYSKEYDOWN)
  129. {
  130. var vkCode = Marshal.ReadInt32(lParam);
  131. var keyData = (Keys)vkCode;
  132. var e = new KeyEventArgs(keyData);
  133. OnKeyDown(e);
  134. suppressKeyPress = e.SuppressKeyPress;
  135. }
  136. }
  137. if (suppressKeyPress)
  138. {
  139. return IntPtr.Zero;
  140. }
  141. return CallNextHookEx(_hookID, nCode, wParam, lParam);
  142. }
  143. /// <summary>
  144. /// Delegate LowLevelKeyboardProc
  145. /// </summary>
  146. /// <param name="nCode">The n code.</param>
  147. /// <param name="wParam">The w param.</param>
  148. /// <param name="lParam">The l param.</param>
  149. /// <returns>IntPtr.</returns>
  150. private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
  151. #region Imports
  152. /// <summary>
  153. /// Sets the windows hook ex.
  154. /// </summary>
  155. /// <param name="idHook">The id hook.</param>
  156. /// <param name="lpfn">The LPFN.</param>
  157. /// <param name="hMod">The h mod.</param>
  158. /// <param name="dwThreadId">The dw thread id.</param>
  159. /// <returns>IntPtr.</returns>
  160. [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  161. private static extern IntPtr SetWindowsHookEx(int idHook,
  162. LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);
  163. /// <summary>
  164. /// Unhooks the windows hook ex.
  165. /// </summary>
  166. /// <param name="hhk">The HHK.</param>
  167. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  168. [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  169. [return: MarshalAs(UnmanagedType.Bool)]
  170. private static extern bool UnhookWindowsHookEx(IntPtr hhk);
  171. /// <summary>
  172. /// Calls the next hook ex.
  173. /// </summary>
  174. /// <param name="hhk">The HHK.</param>
  175. /// <param name="nCode">The n code.</param>
  176. /// <param name="wParam">The w param.</param>
  177. /// <param name="lParam">The l param.</param>
  178. /// <returns>IntPtr.</returns>
  179. [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  180. private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode,
  181. IntPtr wParam, IntPtr lParam);
  182. /// <summary>
  183. /// Gets the module handle.
  184. /// </summary>
  185. /// <param name="lpModuleName">Name of the lp module.</param>
  186. /// <returns>IntPtr.</returns>
  187. [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  188. private static extern IntPtr GetModuleHandle(string lpModuleName);
  189. #endregion
  190. }
  191. }