WindowMessageSink.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. // hardcodet.net NotifyIcon for WPF
  2. // Copyright (c) 2009 - 2013 Philipp Sumi
  3. // Contact and Information: http://www.hardcodet.net
  4. //
  5. // This library is free software; you can redistribute it and/or
  6. // modify it under the terms of the Code Project Open License (CPOL);
  7. // either version 1.0 of the License, or (at your option) any later
  8. // version.
  9. //
  10. // The above copyright notice and this permission notice shall be
  11. // included in all copies or substantial portions of the Software.
  12. //
  13. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  14. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  15. // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  16. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  17. // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  18. // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  20. // OTHER DEALINGS IN THE SOFTWARE.
  21. //
  22. // THIS COPYRIGHT NOTICE MAY NOT BE REMOVED FROM THIS FILE
  23. using System;
  24. using System.ComponentModel;
  25. using System.Diagnostics;
  26. namespace Hardcodet.Wpf.TaskbarNotification.Interop
  27. {
  28. /// <summary>
  29. /// Receives messages from the taskbar icon through
  30. /// window messages of an underlying helper window.
  31. /// </summary>
  32. public class WindowMessageSink : IDisposable
  33. {
  34. #region members
  35. /// <summary>
  36. /// The ID of messages that are received from the the
  37. /// taskbar icon.
  38. /// </summary>
  39. public const int CallbackMessageId = 0x400;
  40. /// <summary>
  41. /// The ID of the message that is being received if the
  42. /// taskbar is (re)started.
  43. /// </summary>
  44. private uint taskbarRestartMessageId;
  45. /// <summary>
  46. /// Used to track whether a mouse-up event is just
  47. /// the aftermath of a double-click and therefore needs
  48. /// to be suppressed.
  49. /// </summary>
  50. private bool isDoubleClick;
  51. /// <summary>
  52. /// A delegate that processes messages of the hidden
  53. /// native window that receives window messages. Storing
  54. /// this reference makes sure we don't loose our reference
  55. /// to the message window.
  56. /// </summary>
  57. private WindowProcedureHandler messageHandler;
  58. /// <summary>
  59. /// Window class ID.
  60. /// </summary>
  61. internal string WindowId { get; private set; }
  62. /// <summary>
  63. /// Handle for the message window.
  64. /// </summary>
  65. internal IntPtr MessageWindowHandle { get; private set; }
  66. /// <summary>
  67. /// The version of the underlying icon. Defines how
  68. /// incoming messages are interpreted.
  69. /// </summary>
  70. public NotifyIconVersion Version { get; set; }
  71. #endregion
  72. #region events
  73. /// <summary>
  74. /// The custom tooltip should be closed or hidden.
  75. /// </summary>
  76. public event Action<bool> ChangeToolTipStateRequest;
  77. /// <summary>
  78. /// Fired in case the user clicked or moved within
  79. /// the taskbar icon area.
  80. /// </summary>
  81. public event Action<MouseEvent> MouseEventReceived;
  82. /// <summary>
  83. /// Fired if a balloon ToolTip was either displayed
  84. /// or closed (indicated by the boolean flag).
  85. /// </summary>
  86. public event Action<bool> BalloonToolTipChanged;
  87. /// <summary>
  88. /// Fired if the taskbar was created or restarted. Requires the taskbar
  89. /// icon to be reset.
  90. /// </summary>
  91. public event Action TaskbarCreated;
  92. #endregion
  93. #region construction
  94. /// <summary>
  95. /// Creates a new message sink that receives message from
  96. /// a given taskbar icon.
  97. /// </summary>
  98. /// <param name="version"></param>
  99. public WindowMessageSink(NotifyIconVersion version)
  100. {
  101. Version = version;
  102. CreateMessageWindow();
  103. }
  104. private WindowMessageSink()
  105. {
  106. }
  107. /// <summary>
  108. /// Creates a dummy instance that provides an empty
  109. /// pointer rather than a real window handler.<br/>
  110. /// Used at design time.
  111. /// </summary>
  112. /// <returns>WindowMessageSink</returns>
  113. internal static WindowMessageSink CreateEmpty()
  114. {
  115. return new WindowMessageSink
  116. {
  117. MessageWindowHandle = IntPtr.Zero,
  118. Version = NotifyIconVersion.Vista
  119. };
  120. }
  121. #endregion
  122. #region CreateMessageWindow
  123. /// <summary>
  124. /// Creates the helper message window that is used
  125. /// to receive messages from the taskbar icon.
  126. /// </summary>
  127. private void CreateMessageWindow()
  128. {
  129. //generate a unique ID for the window
  130. WindowId = "WPFTaskbarIcon_" + Guid.NewGuid();
  131. //register window message handler
  132. messageHandler = OnWindowMessageReceived;
  133. // Create a simple window class which is reference through
  134. //the messageHandler delegate
  135. WindowClass wc;
  136. wc.style = 0;
  137. wc.lpfnWndProc = messageHandler;
  138. wc.cbClsExtra = 0;
  139. wc.cbWndExtra = 0;
  140. wc.hInstance = IntPtr.Zero;
  141. wc.hIcon = IntPtr.Zero;
  142. wc.hCursor = IntPtr.Zero;
  143. wc.hbrBackground = IntPtr.Zero;
  144. wc.lpszMenuName = string.Empty;
  145. wc.lpszClassName = WindowId;
  146. // Register the window class
  147. WinApi.RegisterClass(ref wc);
  148. // Get the message used to indicate the taskbar has been restarted
  149. // This is used to re-add icons when the taskbar restarts
  150. taskbarRestartMessageId = WinApi.RegisterWindowMessage("TaskbarCreated");
  151. // Create the message window
  152. MessageWindowHandle = WinApi.CreateWindowEx(0, WindowId, "", 0, 0, 0, 1, 1, IntPtr.Zero, IntPtr.Zero,
  153. IntPtr.Zero, IntPtr.Zero);
  154. if (MessageWindowHandle == IntPtr.Zero)
  155. {
  156. throw new Win32Exception("Message window handle was not a valid pointer");
  157. }
  158. }
  159. #endregion
  160. #region Handle Window Messages
  161. /// <summary>
  162. /// Callback method that receives messages from the taskbar area.
  163. /// </summary>
  164. private IntPtr OnWindowMessageReceived(IntPtr hWnd, uint messageId, IntPtr wParam, IntPtr lParam)
  165. {
  166. if (messageId == taskbarRestartMessageId)
  167. {
  168. //recreate the icon if the taskbar was restarted (e.g. due to Win Explorer shutdown)
  169. var listener = TaskbarCreated;
  170. listener?.Invoke();
  171. }
  172. //forward message
  173. ProcessWindowMessage(messageId, wParam, lParam);
  174. // Pass the message to the default window procedure
  175. return WinApi.DefWindowProc(hWnd, messageId, wParam, lParam);
  176. }
  177. /// <summary>
  178. /// Processes incoming system messages.
  179. /// </summary>
  180. /// <param name="msg">Callback ID.</param>
  181. /// <param name="wParam">If the version is <see cref="NotifyIconVersion.Vista"/>
  182. /// or higher, this parameter can be used to resolve mouse coordinates.
  183. /// Currently not in use.</param>
  184. /// <param name="lParam">Provides information about the event.</param>
  185. private void ProcessWindowMessage(uint msg, IntPtr wParam, IntPtr lParam)
  186. {
  187. if (msg != CallbackMessageId) return;
  188. var message = (WindowsMessages) lParam.ToInt32();
  189. //Debug.WriteLine("Got message " + message);
  190. switch (message)
  191. {
  192. case WindowsMessages.WM_CONTEXTMENU:
  193. // TODO: Handle WM_CONTEXTMENU, see https://docs.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-shell_notifyiconw
  194. //Debug.WriteLine("Unhandled WM_CONTEXTMENU");
  195. break;
  196. case WindowsMessages.WM_MOUSEMOVE:
  197. MouseEventReceived?.Invoke(MouseEvent.MouseMove);
  198. break;
  199. case WindowsMessages.WM_LBUTTONDOWN:
  200. MouseEventReceived?.Invoke(MouseEvent.IconLeftMouseDown);
  201. break;
  202. case WindowsMessages.WM_LBUTTONUP:
  203. if (!isDoubleClick)
  204. {
  205. MouseEventReceived?.Invoke(MouseEvent.IconLeftMouseUp);
  206. }
  207. isDoubleClick = false;
  208. break;
  209. case WindowsMessages.WM_LBUTTONDBLCLK:
  210. isDoubleClick = true;
  211. MouseEventReceived?.Invoke(MouseEvent.IconDoubleClick);
  212. break;
  213. case WindowsMessages.WM_RBUTTONDOWN:
  214. MouseEventReceived?.Invoke(MouseEvent.IconRightMouseDown);
  215. break;
  216. case WindowsMessages.WM_RBUTTONUP:
  217. MouseEventReceived?.Invoke(MouseEvent.IconRightMouseUp);
  218. break;
  219. case WindowsMessages.WM_RBUTTONDBLCLK:
  220. //double click with right mouse button - do not trigger event
  221. break;
  222. case WindowsMessages.WM_MBUTTONDOWN:
  223. MouseEventReceived?.Invoke(MouseEvent.IconMiddleMouseDown);
  224. break;
  225. case WindowsMessages.WM_MBUTTONUP:
  226. MouseEventReceived?.Invoke(MouseEvent.IconMiddleMouseUp);
  227. break;
  228. case WindowsMessages.WM_MBUTTONDBLCLK:
  229. //double click with middle mouse button - do not trigger event
  230. break;
  231. case WindowsMessages.NIN_BALLOONSHOW:
  232. BalloonToolTipChanged?.Invoke(true);
  233. break;
  234. case WindowsMessages.NIN_BALLOONHIDE:
  235. case WindowsMessages.NIN_BALLOONTIMEOUT:
  236. BalloonToolTipChanged?.Invoke(false);
  237. break;
  238. case WindowsMessages.NIN_BALLOONUSERCLICK:
  239. MouseEventReceived?.Invoke(MouseEvent.BalloonToolTipClicked);
  240. break;
  241. case WindowsMessages.NIN_POPUPOPEN:
  242. ChangeToolTipStateRequest?.Invoke(true);
  243. break;
  244. case WindowsMessages.NIN_POPUPCLOSE:
  245. ChangeToolTipStateRequest?.Invoke(false);
  246. break;
  247. case WindowsMessages.NIN_SELECT:
  248. // TODO: Handle NIN_SELECT see https://docs.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-shell_notifyiconw
  249. //Debug.WriteLine("Unhandled NIN_SELECT");
  250. break;
  251. case WindowsMessages.NIN_KEYSELECT:
  252. // TODO: Handle NIN_KEYSELECT see https://docs.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-shell_notifyiconw
  253. //Debug.WriteLine("Unhandled NIN_KEYSELECT");
  254. break;
  255. default:
  256. //Debug.WriteLine("Unhandled NotifyIcon message ID: " + lParam);
  257. break;
  258. }
  259. }
  260. #endregion
  261. #region Dispose
  262. /// <summary>
  263. /// Set to true as soon as <c>Dispose</c> has been invoked.
  264. /// </summary>
  265. public bool IsDisposed { get; private set; }
  266. /// <summary>
  267. /// Disposes the object.
  268. /// </summary>
  269. /// <remarks>This method is not virtual by design. Derived classes
  270. /// should override <see cref="Dispose(bool)"/>.
  271. /// </remarks>
  272. public void Dispose()
  273. {
  274. Dispose(true);
  275. // This object will be cleaned up by the Dispose method.
  276. // Therefore, you should call GC.SuppressFinalize to
  277. // take this object off the finalization queue
  278. // and prevent finalization code for this object
  279. // from executing a second time.
  280. GC.SuppressFinalize(this);
  281. }
  282. /// <summary>
  283. /// This destructor will run only if the <see cref="Dispose()"/>
  284. /// method does not get called. This gives this base class the
  285. /// opportunity to finalize.
  286. /// <para>
  287. /// Important: Do not provide destructor in types derived from
  288. /// this class.
  289. /// </para>
  290. /// </summary>
  291. ~WindowMessageSink()
  292. {
  293. Dispose(false);
  294. }
  295. /// <summary>
  296. /// Removes the windows hook that receives window
  297. /// messages and closes the underlying helper window.
  298. /// </summary>
  299. private void Dispose(bool disposing)
  300. {
  301. //don't do anything if the component is already disposed
  302. if (IsDisposed) return;
  303. IsDisposed = true;
  304. //always destroy the unmanaged handle (even if called from the GC)
  305. WinApi.DestroyWindow(MessageWindowHandle);
  306. messageHandler = null;
  307. }
  308. #endregion
  309. }
  310. }