TaskbarIcon.cs 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103
  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.Diagnostics;
  25. using System.Drawing;
  26. using System.Threading;
  27. using System.Windows;
  28. using System.Windows.Controls;
  29. using System.Windows.Controls.Primitives;
  30. using System.Windows.Interop;
  31. using System.Windows.Threading;
  32. using Hardcodet.Wpf.TaskbarNotification.Interop;
  33. using Point = Hardcodet.Wpf.TaskbarNotification.Interop.Point;
  34. namespace Hardcodet.Wpf.TaskbarNotification
  35. {
  36. /// <summary>
  37. /// A WPF proxy to for a taskbar icon (NotifyIcon) that sits in the system's
  38. /// taskbar notification area ("system tray").
  39. /// </summary>
  40. public partial class TaskbarIcon : FrameworkElement, IDisposable
  41. {
  42. private readonly object lockObject = new object();
  43. #region Members
  44. /// <summary>
  45. /// Represents the current icon data.
  46. /// </summary>
  47. private NotifyIconData iconData;
  48. /// <summary>
  49. /// Receives messages from the taskbar icon.
  50. /// </summary>
  51. private readonly WindowMessageSink messageSink;
  52. /// <summary>
  53. /// An action that is being invoked if the
  54. /// <see cref="singleClickTimer"/> fires.
  55. /// </summary>
  56. private Action singleClickTimerAction;
  57. /// <summary>
  58. /// A timer that is used to differentiate between single
  59. /// and double clicks.
  60. /// </summary>
  61. private readonly Timer singleClickTimer;
  62. /// <summary>
  63. /// The time we should wait for a double click.
  64. /// </summary>
  65. private int DoubleClickWaitTime => NoLeftClickDelay ? 0 : WinApi.GetDoubleClickTime();
  66. /// <summary>
  67. /// A timer that is used to close open balloon tooltips.
  68. /// </summary>
  69. private readonly Timer balloonCloseTimer;
  70. /// <summary>
  71. /// Indicates whether the taskbar icon has been created or not.
  72. /// </summary>
  73. public bool IsTaskbarIconCreated { get; private set; }
  74. /// <summary>
  75. /// Indicates whether custom tooltips are supported, which depends
  76. /// on the OS. Windows Vista or higher is required in order to
  77. /// support this feature.
  78. /// </summary>
  79. public bool SupportsCustomToolTips => messageSink.Version == NotifyIconVersion.Vista;
  80. /// <summary>
  81. /// Checks whether a non-tooltip popup is currently opened.
  82. /// </summary>
  83. private bool IsPopupOpen
  84. {
  85. get
  86. {
  87. var popup = TrayPopupResolved;
  88. var menu = ContextMenu;
  89. var balloon = CustomBalloon;
  90. return popup != null && popup.IsOpen ||
  91. menu != null && menu.IsOpen ||
  92. balloon != null && balloon.IsOpen;
  93. }
  94. }
  95. #endregion
  96. #region Construction
  97. /// <summary>
  98. /// Initializes the taskbar icon and registers a message listener
  99. /// in order to receive events from the taskbar area.
  100. /// </summary>
  101. public TaskbarIcon()
  102. {
  103. // using dummy sink in design mode
  104. messageSink = Util.IsDesignMode
  105. ? WindowMessageSink.CreateEmpty()
  106. : new WindowMessageSink(NotifyIconVersion.Win95);
  107. // init icon data structure
  108. iconData = NotifyIconData.CreateDefault(messageSink.MessageWindowHandle);
  109. // create the taskbar icon
  110. CreateTaskbarIcon();
  111. // register event listeners
  112. messageSink.MouseEventReceived += OnMouseEvent;
  113. messageSink.TaskbarCreated += OnTaskbarCreated;
  114. messageSink.ChangeToolTipStateRequest += OnToolTipChange;
  115. messageSink.BalloonToolTipChanged += OnBalloonToolTipChanged;
  116. // init single click / balloon timers
  117. singleClickTimer = new Timer(DoSingleClickAction);
  118. balloonCloseTimer = new Timer(CloseBalloonCallback);
  119. // register listener in order to get notified when the application closes
  120. if (Application.Current != null)
  121. {
  122. Application.Current.Exit += OnExit;
  123. }
  124. }
  125. #endregion
  126. #region Custom Balloons
  127. /// <summary>
  128. /// A delegate to handle customer popup positions.
  129. /// </summary>
  130. public delegate Point GetCustomPopupPosition();
  131. /// <summary>
  132. /// Specify a custom popup position
  133. /// </summary>
  134. public GetCustomPopupPosition CustomPopupPosition { get; set; }
  135. /// <summary>
  136. /// Returns the location of the system tray
  137. /// </summary>
  138. /// <returns>Point</returns>
  139. public Point GetPopupTrayPosition()
  140. {
  141. return TrayInfo.GetTrayLocation();
  142. }
  143. /// <summary>
  144. /// Shows a custom control as a tooltip in the tray location.
  145. /// </summary>
  146. /// <param name="balloon"></param>
  147. /// <param name="animation">An optional animation for the popup.</param>
  148. /// <param name="timeout">The time after which the popup is being closed.
  149. /// Submit null in order to keep the balloon open indefinitely
  150. /// </param>
  151. /// <exception cref="ArgumentNullException">If <paramref name="balloon"/>
  152. /// is a null reference.</exception>
  153. public void ShowCustomBalloon(UIElement balloon, PopupAnimation animation, int? timeout)
  154. {
  155. var dispatcher = this.GetDispatcher();
  156. if (!dispatcher.CheckAccess())
  157. {
  158. var action = new Action(() => ShowCustomBalloon(balloon, animation, timeout));
  159. dispatcher.Invoke(DispatcherPriority.Normal, action);
  160. return;
  161. }
  162. if (balloon == null) throw new ArgumentNullException(nameof(balloon));
  163. if (timeout.HasValue && timeout < 500)
  164. {
  165. string msg = "Invalid timeout of {0} milliseconds. Timeout must be at least 500 ms";
  166. msg = string.Format(msg, timeout);
  167. throw new ArgumentOutOfRangeException(nameof(timeout), msg);
  168. }
  169. EnsureNotDisposed();
  170. // make sure we don't have an open balloon
  171. lock (lockObject)
  172. {
  173. CloseBalloon();
  174. }
  175. // create an invisible popup that hosts the UIElement
  176. Popup popup = new Popup
  177. {
  178. AllowsTransparency = true
  179. };
  180. // provide the popup with the taskbar icon's data context
  181. UpdateDataContext(popup, null, DataContext);
  182. // don't animate by default - developers can use attached events or override
  183. popup.PopupAnimation = animation;
  184. // in case the balloon is cleaned up through routed events, the
  185. // control didn't remove the balloon from its parent popup when
  186. // if was closed the last time - just make sure it doesn't have
  187. // a parent that is a popup
  188. var parent = LogicalTreeHelper.GetParent(balloon) as Popup;
  189. if (parent != null) parent.Child = null;
  190. if (parent != null)
  191. {
  192. string msg = "Cannot display control [{0}] in a new balloon popup - that control already has a parent. You may consider creating new balloons every time you want to show one.";
  193. msg = string.Format(msg, balloon);
  194. throw new InvalidOperationException(msg);
  195. }
  196. popup.Child = balloon;
  197. //don't set the PlacementTarget as it causes the popup to become hidden if the
  198. //TaskbarIcon's parent is hidden, too...
  199. //popup.PlacementTarget = this;
  200. popup.Placement = PlacementMode.AbsolutePoint;
  201. popup.StaysOpen = true;
  202. Point position = CustomPopupPosition != null ? CustomPopupPosition() : GetPopupTrayPosition();
  203. popup.HorizontalOffset = position.X - 1;
  204. popup.VerticalOffset = position.Y - 1;
  205. //store reference
  206. lock (lockObject)
  207. {
  208. SetCustomBalloon(popup);
  209. }
  210. // assign this instance as an attached property
  211. SetParentTaskbarIcon(balloon, this);
  212. // fire attached event
  213. RaiseBalloonShowingEvent(balloon, this);
  214. // display item
  215. popup.IsOpen = true;
  216. if (timeout.HasValue)
  217. {
  218. // register timer to close the popup
  219. balloonCloseTimer.Change(timeout.Value, Timeout.Infinite);
  220. }
  221. }
  222. /// <summary>
  223. /// Resets the closing timeout, which effectively
  224. /// keeps a displayed balloon message open until
  225. /// it is either closed programmatically through
  226. /// <see cref="CloseBalloon"/> or due to a new
  227. /// message being displayed.
  228. /// </summary>
  229. public void ResetBalloonCloseTimer()
  230. {
  231. if (IsDisposed) return;
  232. lock (lockObject)
  233. {
  234. //reset timer in any case
  235. balloonCloseTimer.Change(Timeout.Infinite, Timeout.Infinite);
  236. }
  237. }
  238. /// <summary>
  239. /// Closes the current <see cref="CustomBalloon"/>, if the
  240. /// property is set.
  241. /// </summary>
  242. public void CloseBalloon()
  243. {
  244. if (IsDisposed) return;
  245. Dispatcher dispatcher = this.GetDispatcher();
  246. if (!dispatcher.CheckAccess())
  247. {
  248. Action action = CloseBalloon;
  249. dispatcher.Invoke(DispatcherPriority.Normal, action);
  250. return;
  251. }
  252. lock (lockObject)
  253. {
  254. // reset timer in any case
  255. balloonCloseTimer.Change(Timeout.Infinite, Timeout.Infinite);
  256. // reset old popup, if we still have one
  257. Popup popup = CustomBalloon;
  258. if (popup == null)
  259. {
  260. return;
  261. }
  262. UIElement element = popup.Child;
  263. // announce closing
  264. RoutedEventArgs eventArgs = RaiseBalloonClosingEvent(element, this);
  265. if (!eventArgs.Handled)
  266. {
  267. // if the event was handled, clear the reference to the popup,
  268. // but don't close it - the handling code has to manage this stuff now
  269. // close the popup
  270. popup.IsOpen = false;
  271. // remove the reference of the popup to the balloon in case we want to reuse
  272. // the balloon (then added to a new popup)
  273. popup.Child = null;
  274. // reset attached property
  275. if (element != null) SetParentTaskbarIcon(element, null);
  276. }
  277. // remove custom balloon anyway
  278. SetCustomBalloon(null);
  279. }
  280. }
  281. /// <summary>
  282. /// Timer-invoke event which closes the currently open balloon and
  283. /// resets the <see cref="CustomBalloon"/> dependency property.
  284. /// </summary>
  285. private void CloseBalloonCallback(object state)
  286. {
  287. if (IsDisposed) return;
  288. // switch to UI thread
  289. Action action = CloseBalloon;
  290. this.GetDispatcher().Invoke(action);
  291. }
  292. #endregion
  293. #region Process Incoming Mouse Events
  294. /// <summary>
  295. /// Processes mouse events, which are bubbled
  296. /// through the class' routed events, trigger
  297. /// certain actions (e.g. show a popup), or
  298. /// both.
  299. /// </summary>
  300. /// <param name="me">Event flag.</param>
  301. private void OnMouseEvent(MouseEvent me)
  302. {
  303. if (IsDisposed) return;
  304. switch (me)
  305. {
  306. case MouseEvent.MouseMove:
  307. RaiseTrayMouseMoveEvent();
  308. // immediately return - there's nothing left to evaluate
  309. return;
  310. case MouseEvent.IconRightMouseDown:
  311. RaiseTrayRightMouseDownEvent();
  312. break;
  313. case MouseEvent.IconLeftMouseDown:
  314. RaiseTrayLeftMouseDownEvent();
  315. break;
  316. case MouseEvent.IconRightMouseUp:
  317. RaiseTrayRightMouseUpEvent();
  318. break;
  319. case MouseEvent.IconLeftMouseUp:
  320. RaiseTrayLeftMouseUpEvent();
  321. break;
  322. case MouseEvent.IconMiddleMouseDown:
  323. RaiseTrayMiddleMouseDownEvent();
  324. break;
  325. case MouseEvent.IconMiddleMouseUp:
  326. RaiseTrayMiddleMouseUpEvent();
  327. break;
  328. case MouseEvent.IconDoubleClick:
  329. // cancel single click timer
  330. singleClickTimer.Change(Timeout.Infinite, Timeout.Infinite);
  331. // bubble event
  332. RaiseTrayMouseDoubleClickEvent();
  333. break;
  334. case MouseEvent.BalloonToolTipClicked:
  335. RaiseTrayBalloonTipClickedEvent();
  336. break;
  337. default:
  338. throw new ArgumentOutOfRangeException(nameof(me), "Missing handler for mouse event flag: " + me);
  339. }
  340. // get mouse coordinates
  341. Point cursorPosition = new Point();
  342. if (messageSink.Version == NotifyIconVersion.Vista)
  343. {
  344. // physical cursor position is supported for Vista and above
  345. WinApi.GetPhysicalCursorPos(ref cursorPosition);
  346. }
  347. else
  348. {
  349. WinApi.GetCursorPos(ref cursorPosition);
  350. }
  351. cursorPosition = TrayInfo.GetDeviceCoordinates(cursorPosition);
  352. bool isLeftClickCommandInvoked = false;
  353. // show popup, if requested
  354. if (me.IsMatch(PopupActivation))
  355. {
  356. if (me == MouseEvent.IconLeftMouseUp)
  357. {
  358. // show popup once we are sure it's not a double click
  359. singleClickTimerAction = () =>
  360. {
  361. LeftClickCommand.ExecuteIfEnabled(LeftClickCommandParameter, LeftClickCommandTarget ?? this);
  362. ShowTrayPopup(cursorPosition);
  363. };
  364. singleClickTimer.Change(DoubleClickWaitTime, Timeout.Infinite);
  365. isLeftClickCommandInvoked = true;
  366. }
  367. else
  368. {
  369. // show popup immediately
  370. ShowTrayPopup(cursorPosition);
  371. }
  372. }
  373. // show context menu, if requested
  374. if (me.IsMatch(MenuActivation))
  375. {
  376. if (me == MouseEvent.IconLeftMouseUp)
  377. {
  378. // show context menu once we are sure it's not a double click
  379. singleClickTimerAction = () =>
  380. {
  381. LeftClickCommand.ExecuteIfEnabled(LeftClickCommandParameter, LeftClickCommandTarget ?? this);
  382. ShowContextMenu(cursorPosition);
  383. };
  384. singleClickTimer.Change(DoubleClickWaitTime, Timeout.Infinite);
  385. isLeftClickCommandInvoked = true;
  386. }
  387. else
  388. {
  389. // show context menu immediately
  390. ShowContextMenu(cursorPosition);
  391. }
  392. }
  393. // make sure the left click command is invoked on mouse clicks
  394. if (me == MouseEvent.IconLeftMouseUp && !isLeftClickCommandInvoked)
  395. {
  396. // show context menu once we are sure it's not a double click
  397. singleClickTimerAction =
  398. () =>
  399. {
  400. LeftClickCommand.ExecuteIfEnabled(LeftClickCommandParameter, LeftClickCommandTarget ?? this);
  401. };
  402. singleClickTimer.Change(DoubleClickWaitTime, Timeout.Infinite);
  403. }
  404. }
  405. #endregion
  406. #region ToolTips
  407. /// <summary>
  408. /// Displays a custom tooltip, if available. This method is only
  409. /// invoked for Windows Vista and above.
  410. /// </summary>
  411. /// <param name="visible">Whether to show or hide the tooltip.</param>
  412. private void OnToolTipChange(bool visible)
  413. {
  414. // if we don't have a tooltip, there's nothing to do here...
  415. if (TrayToolTipResolved == null) return;
  416. if (visible)
  417. {
  418. if (IsPopupOpen)
  419. {
  420. // ignore if we are already displaying something down there
  421. return;
  422. }
  423. var args = RaisePreviewTrayToolTipOpenEvent();
  424. if (args.Handled) return;
  425. TrayToolTipResolved.IsOpen = true;
  426. // raise attached event first
  427. if (TrayToolTip != null) RaiseToolTipOpenedEvent(TrayToolTip);
  428. // bubble routed event
  429. RaiseTrayToolTipOpenEvent();
  430. }
  431. else
  432. {
  433. var args = RaisePreviewTrayToolTipCloseEvent();
  434. if (args.Handled) return;
  435. // raise attached event first
  436. if (TrayToolTip != null) RaiseToolTipCloseEvent(TrayToolTip);
  437. TrayToolTipResolved.IsOpen = false;
  438. // bubble event
  439. RaiseTrayToolTipCloseEvent();
  440. }
  441. }
  442. /// <summary>
  443. /// Creates a <see cref="ToolTip"/> control that either
  444. /// wraps the currently set <see cref="TrayToolTip"/>
  445. /// control or the <see cref="ToolTipText"/> string.<br/>
  446. /// If <see cref="TrayToolTip"/> itself is already
  447. /// a <see cref="ToolTip"/> instance, it will be used directly.
  448. /// </summary>
  449. /// <remarks>We use a <see cref="ToolTip"/> rather than
  450. /// <see cref="Popup"/> because there was no way to prevent a
  451. /// popup from causing cyclic open/close commands if it was
  452. /// placed under the mouse. ToolTip internally uses a Popup of
  453. /// its own, but takes advance of Popup's internal <see cref="UIElement.IsHitTestVisible"/>
  454. /// property which prevents this issue.</remarks>
  455. private void CreateCustomToolTip()
  456. {
  457. // check if the item itself is a tooltip
  458. ToolTip tt = TrayToolTip as ToolTip;
  459. if (tt == null && TrayToolTip != null)
  460. {
  461. // create an invisible wrapper tooltip that hosts the UIElement
  462. tt = new ToolTip
  463. {
  464. Placement = PlacementMode.Mouse,
  465. // do *not* set the placement target, as it causes the popup to become hidden if the
  466. // TaskbarIcon's parent is hidden, too. At runtime, the parent can be resolved through
  467. // the ParentTaskbarIcon attached dependency property:
  468. // PlacementTarget = this;
  469. // make sure the tooltip is invisible
  470. HasDropShadow = false,
  471. BorderThickness = new Thickness(0),
  472. Background = System.Windows.Media.Brushes.Transparent,
  473. // setting the
  474. StaysOpen = true,
  475. Content = TrayToolTip
  476. };
  477. }
  478. else if (tt == null && !string.IsNullOrEmpty(ToolTipText))
  479. {
  480. // create a simple tooltip for the ToolTipText string
  481. tt = new ToolTip
  482. {
  483. Content = ToolTipText
  484. };
  485. }
  486. // the tooltip explicitly gets the DataContext of this instance.
  487. // If there is no DataContext, the TaskbarIcon assigns itself
  488. if (tt != null)
  489. {
  490. UpdateDataContext(tt, null, DataContext);
  491. }
  492. // store a reference to the used tooltip
  493. SetTrayToolTipResolved(tt);
  494. }
  495. /// <summary>
  496. /// Sets tooltip settings for the class depending on defined
  497. /// dependency properties and OS support.
  498. /// </summary>
  499. private void WriteToolTipSettings()
  500. {
  501. const IconDataMembers flags = IconDataMembers.Tip;
  502. iconData.ToolTipText = ToolTipText;
  503. if (messageSink.Version == NotifyIconVersion.Vista)
  504. {
  505. // we need to set a tooltip text to get tooltip events from the
  506. // taskbar icon
  507. if (string.IsNullOrEmpty(iconData.ToolTipText) && TrayToolTipResolved != null)
  508. {
  509. // if we have not tooltip text but a custom tooltip, we
  510. // need to set a dummy value (we're displaying the ToolTip control, not the string)
  511. iconData.ToolTipText = "ToolTip";
  512. }
  513. }
  514. // update the tooltip text
  515. Util.WriteIconData(ref iconData, NotifyCommand.Modify, flags);
  516. }
  517. #endregion
  518. #region Custom Popup
  519. /// <summary>
  520. /// Creates a <see cref="ToolTip"/> control that either
  521. /// wraps the currently set <see cref="TrayToolTip"/>
  522. /// control or the <see cref="ToolTipText"/> string.<br/>
  523. /// If <see cref="TrayToolTip"/> itself is already
  524. /// a <see cref="ToolTip"/> instance, it will be used directly.
  525. /// </summary>
  526. /// <remarks>We use a <see cref="ToolTip"/> rather than
  527. /// <see cref="Popup"/> because there was no way to prevent a
  528. /// popup from causing cyclic open/close commands if it was
  529. /// placed under the mouse. ToolTip internally uses a Popup of
  530. /// its own, but takes advance of Popup's internal <see cref="UIElement.IsHitTestVisible"/>
  531. /// property which prevents this issue.</remarks>
  532. private void CreatePopup()
  533. {
  534. // check if the item itself is a popup
  535. Popup popup = TrayPopup as Popup;
  536. if (popup == null && TrayPopup != null)
  537. {
  538. // create an invisible popup that hosts the UIElement
  539. popup = new Popup
  540. {
  541. AllowsTransparency = true,
  542. // don't animate by default - developers can use attached events or override
  543. PopupAnimation = PopupAnimation.None,
  544. // the CreateRootPopup method outputs binding errors in the debug window because
  545. // it tries to bind to "Popup-specific" properties in case they are provided by the child.
  546. // We don't need that so just assign the control as the child.
  547. Child = TrayPopup,
  548. // do *not* set the placement target, as it causes the popup to become hidden if the
  549. // TaskbarIcon's parent is hidden, too. At runtime, the parent can be resolved through
  550. // the ParentTaskbarIcon attached dependency property:
  551. // PlacementTarget = this;
  552. Placement = PlacementMode.AbsolutePoint,
  553. StaysOpen = false
  554. };
  555. }
  556. // the popup explicitly gets the DataContext of this instance.
  557. // If there is no DataContext, the TaskbarIcon assigns itself
  558. if (popup != null)
  559. {
  560. UpdateDataContext(popup, null, DataContext);
  561. }
  562. // store a reference to the used tooltip
  563. SetTrayPopupResolved(popup);
  564. }
  565. /// <summary>
  566. /// Displays the <see cref="TrayPopup"/> control if it was set.
  567. /// </summary>
  568. private void ShowTrayPopup(Point cursorPosition)
  569. {
  570. if (IsDisposed) return;
  571. // raise preview event no matter whether popup is currently set
  572. // or not (enables client to set it on demand)
  573. var args = RaisePreviewTrayPopupOpenEvent();
  574. if (args.Handled) return;
  575. if (TrayPopup == null)
  576. {
  577. return;
  578. }
  579. // use absolute position, but place the popup centered above the icon
  580. TrayPopupResolved.Placement = PlacementMode.AbsolutePoint;
  581. TrayPopupResolved.HorizontalOffset = cursorPosition.X;
  582. TrayPopupResolved.VerticalOffset = cursorPosition.Y;
  583. // open popup
  584. TrayPopupResolved.IsOpen = true;
  585. IntPtr handle = IntPtr.Zero;
  586. if (TrayPopupResolved.Child != null)
  587. {
  588. // try to get a handle on the popup itself (via its child)
  589. HwndSource source = (HwndSource)PresentationSource.FromVisual(TrayPopupResolved.Child);
  590. if (source != null) handle = source.Handle;
  591. }
  592. // if we don't have a handle for the popup, fall back to the message sink
  593. if (handle == IntPtr.Zero) handle = messageSink.MessageWindowHandle;
  594. // activate either popup or message sink to track deactivation.
  595. // otherwise, the popup does not close if the user clicks somewhere else
  596. WinApi.SetForegroundWindow(handle);
  597. // raise attached event - item should never be null unless developers
  598. // changed the CustomPopup directly...
  599. if (TrayPopup != null) RaisePopupOpenedEvent(TrayPopup);
  600. // bubble routed event
  601. RaiseTrayPopupOpenEvent();
  602. }
  603. #endregion
  604. #region Context Menu
  605. /// <summary>
  606. /// Displays the <see cref="ContextMenu"/> if it was set.
  607. /// </summary>
  608. private void ShowContextMenu(Point cursorPosition)
  609. {
  610. if (IsDisposed) return;
  611. // raise preview event no matter whether context menu is currently set
  612. // or not (enables client to set it on demand)
  613. var args = RaisePreviewTrayContextMenuOpenEvent();
  614. if (args.Handled) return;
  615. if (ContextMenu == null)
  616. {
  617. return;
  618. }
  619. // use absolute positioning. We need to set the coordinates, or a delayed opening
  620. // (e.g. when left-clicked) opens the context menu at the wrong place if the mouse
  621. // is moved!
  622. ContextMenu.Placement = PlacementMode.AbsolutePoint;
  623. ContextMenu.HorizontalOffset = cursorPosition.X;
  624. ContextMenu.VerticalOffset = cursorPosition.Y;
  625. ContextMenu.IsOpen = true;
  626. IntPtr handle = IntPtr.Zero;
  627. // try to get a handle on the context itself
  628. HwndSource source = (HwndSource)PresentationSource.FromVisual(ContextMenu);
  629. if (source != null)
  630. {
  631. handle = source.Handle;
  632. }
  633. // if we don't have a handle for the popup, fall back to the message sink
  634. if (handle == IntPtr.Zero) handle = messageSink.MessageWindowHandle;
  635. // activate the context menu or the message window to track deactivation - otherwise, the context menu
  636. // does not close if the user clicks somewhere else. With the message window
  637. // fallback, the context menu can't receive keyboard events - should not happen though
  638. WinApi.SetForegroundWindow(handle);
  639. // bubble event
  640. RaiseTrayContextMenuOpenEvent();
  641. }
  642. #endregion
  643. #region Balloon Tips
  644. /// <summary>
  645. /// Bubbles events if a balloon ToolTip was displayed
  646. /// or removed.
  647. /// </summary>
  648. /// <param name="visible">Whether the ToolTip was just displayed
  649. /// or removed.</param>
  650. private void OnBalloonToolTipChanged(bool visible)
  651. {
  652. if (visible)
  653. {
  654. RaiseTrayBalloonTipShownEvent();
  655. }
  656. else
  657. {
  658. RaiseTrayBalloonTipClosedEvent();
  659. }
  660. }
  661. /// <summary>
  662. /// Displays a balloon tip with the specified title,
  663. /// text, and icon in the taskbar for the specified time period.
  664. /// </summary>
  665. /// <param name="title">The title to display on the balloon tip.</param>
  666. /// <param name="message">The text to display on the balloon tip.</param>
  667. /// <param name="symbol">A symbol that indicates the severity.</param>
  668. public void ShowBalloonTip(string title, string message, BalloonIcon symbol)
  669. {
  670. lock (lockObject)
  671. {
  672. ShowBalloonTip(title, message, symbol.GetBalloonFlag(), IntPtr.Zero);
  673. }
  674. }
  675. /// <summary>
  676. /// Displays a balloon tip with the specified title,
  677. /// text, and a custom icon in the taskbar for the specified time period.
  678. /// </summary>
  679. /// <param name="title">The title to display on the balloon tip.</param>
  680. /// <param name="message">The text to display on the balloon tip.</param>
  681. /// <param name="customIcon">A custom icon.</param>
  682. /// <param name="largeIcon">True to allow large icons (Windows Vista and later).</param>
  683. /// <exception cref="ArgumentNullException">If <paramref name="customIcon"/>
  684. /// is a null reference.</exception>
  685. public void ShowBalloonTip(string title, string message, Icon customIcon, bool largeIcon = false)
  686. {
  687. if (customIcon == null) throw new ArgumentNullException(nameof(customIcon));
  688. lock (lockObject)
  689. {
  690. var flags = BalloonFlags.User;
  691. if (largeIcon)
  692. {
  693. // ReSharper disable once BitwiseOperatorOnEnumWithoutFlags
  694. flags |= BalloonFlags.LargeIcon;
  695. }
  696. ShowBalloonTip(title, message, flags, customIcon.Handle);
  697. }
  698. }
  699. /// <summary>
  700. /// Invokes <see cref="WinApi.Shell_NotifyIcon"/> in order to display
  701. /// a given balloon ToolTip.
  702. /// </summary>
  703. /// <param name="title">The title to display on the balloon tip.</param>
  704. /// <param name="message">The text to display on the balloon tip.</param>
  705. /// <param name="flags">Indicates what icon to use.</param>
  706. /// <param name="balloonIconHandle">A handle to a custom icon, if any, or
  707. /// <see cref="IntPtr.Zero"/>.</param>
  708. private void ShowBalloonTip(string title, string message, BalloonFlags flags, IntPtr balloonIconHandle)
  709. {
  710. EnsureNotDisposed();
  711. iconData.BalloonText = message ?? string.Empty;
  712. iconData.BalloonTitle = title ?? string.Empty;
  713. iconData.BalloonFlags = flags;
  714. iconData.CustomBalloonIconHandle = balloonIconHandle;
  715. Util.WriteIconData(ref iconData, NotifyCommand.Modify, IconDataMembers.Info | IconDataMembers.Icon);
  716. }
  717. /// <summary>
  718. /// Hides a balloon ToolTip, if any is displayed.
  719. /// </summary>
  720. public void HideBalloonTip()
  721. {
  722. EnsureNotDisposed();
  723. // reset balloon by just setting the info to an empty string
  724. iconData.BalloonText = iconData.BalloonTitle = string.Empty;
  725. Util.WriteIconData(ref iconData, NotifyCommand.Modify, IconDataMembers.Info);
  726. }
  727. #endregion
  728. #region Single Click Timer event
  729. /// <summary>
  730. /// Performs a delayed action if the user requested an action
  731. /// based on a single click of the left mouse.<br/>
  732. /// This method is invoked by the <see cref="singleClickTimer"/>.
  733. /// </summary>
  734. private void DoSingleClickAction(object state)
  735. {
  736. if (IsDisposed) return;
  737. // run action
  738. Action action = singleClickTimerAction;
  739. if (action != null)
  740. {
  741. // cleanup action
  742. singleClickTimerAction = null;
  743. // switch to UI thread
  744. this.GetDispatcher().Invoke(action);
  745. }
  746. }
  747. #endregion
  748. #region Set Version (API)
  749. /// <summary>
  750. /// Sets the version flag for the <see cref="iconData"/>.
  751. /// </summary>
  752. private void SetVersion()
  753. {
  754. iconData.VersionOrTimeout = (uint)NotifyIconVersion.Vista;
  755. bool status = WinApi.Shell_NotifyIcon(NotifyCommand.SetVersion, ref iconData);
  756. if (!status)
  757. {
  758. iconData.VersionOrTimeout = (uint)NotifyIconVersion.Win2000;
  759. status = Util.WriteIconData(ref iconData, NotifyCommand.SetVersion);
  760. }
  761. if (!status)
  762. {
  763. iconData.VersionOrTimeout = (uint)NotifyIconVersion.Win95;
  764. status = Util.WriteIconData(ref iconData, NotifyCommand.SetVersion);
  765. }
  766. if (!status)
  767. {
  768. Debug.Fail("Could not set version");
  769. }
  770. }
  771. #endregion
  772. #region Create / Remove Taskbar Icon
  773. /// <summary>
  774. /// Recreates the taskbar icon if the whole taskbar was
  775. /// recreated (e.g. because Explorer was shut down).
  776. /// </summary>
  777. private void OnTaskbarCreated()
  778. {
  779. IsTaskbarIconCreated = false;
  780. CreateTaskbarIcon();
  781. }
  782. /// <summary>
  783. /// Creates the taskbar icon. This message is invoked during initialization,
  784. /// if the taskbar is restarted, and whenever the icon is displayed.
  785. /// </summary>
  786. private void CreateTaskbarIcon()
  787. {
  788. lock (lockObject)
  789. {
  790. if (IsTaskbarIconCreated)
  791. {
  792. return;
  793. }
  794. const IconDataMembers members = IconDataMembers.Message
  795. | IconDataMembers.Icon
  796. | IconDataMembers.Tip;
  797. //write initial configuration
  798. var status = Util.WriteIconData(ref iconData, NotifyCommand.Add, members);
  799. if (!status)
  800. {
  801. // couldn't create the icon - we can assume this is because explorer is not running (yet!)
  802. // -> try a bit later again rather than throwing an exception. Typically, if the windows
  803. // shell is being loaded later, this method is being re-invoked from OnTaskbarCreated
  804. // (we could also retry after a delay, but that's currently YAGNI)
  805. return;
  806. }
  807. //set to most recent version
  808. SetVersion();
  809. messageSink.Version = (NotifyIconVersion)iconData.VersionOrTimeout;
  810. IsTaskbarIconCreated = true;
  811. }
  812. }
  813. /// <summary>
  814. /// Closes the taskbar icon if required.
  815. /// </summary>
  816. private void RemoveTaskbarIcon()
  817. {
  818. lock (lockObject)
  819. {
  820. // make sure we didn't schedule a creation
  821. if (!IsTaskbarIconCreated)
  822. {
  823. return;
  824. }
  825. Util.WriteIconData(ref iconData, NotifyCommand.Delete, IconDataMembers.Message);
  826. IsTaskbarIconCreated = false;
  827. }
  828. }
  829. #endregion
  830. #region Dispose / Exit
  831. /// <summary>
  832. /// Set to true as soon as <c>Dispose</c> has been invoked.
  833. /// </summary>
  834. public bool IsDisposed { get; private set; }
  835. /// <summary>
  836. /// Checks if the object has been disposed and
  837. /// raises a <see cref="ObjectDisposedException"/> in case
  838. /// the <see cref="IsDisposed"/> flag is true.
  839. /// </summary>
  840. private void EnsureNotDisposed()
  841. {
  842. if (IsDisposed) throw new ObjectDisposedException(Name ?? GetType().FullName);
  843. }
  844. /// <summary>
  845. /// Disposes the class if the application exits.
  846. /// </summary>
  847. private void OnExit(object sender, EventArgs e)
  848. {
  849. Dispose();
  850. }
  851. /// <summary>
  852. /// This destructor will run only if the <see cref="Dispose()"/>
  853. /// method does not get called. This gives this base class the
  854. /// opportunity to finalize.
  855. /// <para>
  856. /// Important: Do not provide destructor in types derived from this class.
  857. /// </para>
  858. /// </summary>
  859. ~TaskbarIcon()
  860. {
  861. Dispose(false);
  862. }
  863. /// <summary>
  864. /// Disposes the object.
  865. /// </summary>
  866. /// <remarks>This method is not virtual by design. Derived classes
  867. /// should override <see cref="Dispose(bool)"/>.
  868. /// </remarks>
  869. public void Dispose()
  870. {
  871. Dispose(true);
  872. // This object will be cleaned up by the Dispose method.
  873. // Therefore, you should call GC.SuppressFinalize to
  874. // take this object off the finalization queue
  875. // and prevent finalization code for this object
  876. // from executing a second time.
  877. GC.SuppressFinalize(this);
  878. }
  879. /// <summary>
  880. /// Closes the tray and releases all resources.
  881. /// </summary>
  882. /// <summary>
  883. /// <c>Dispose(bool disposing)</c> executes in two distinct scenarios.
  884. /// If disposing equals <c>true</c>, the method has been called directly
  885. /// or indirectly by a user's code. Managed and unmanaged resources
  886. /// can be disposed.
  887. /// </summary>
  888. /// <param name="disposing">If disposing equals <c>false</c>, the method
  889. /// has been called by the runtime from inside the finalizer and you
  890. /// should not reference other objects. Only unmanaged resources can
  891. /// be disposed.</param>
  892. /// <remarks>Check the <see cref="IsDisposed"/> property to determine whether
  893. /// the method has already been called.</remarks>
  894. private void Dispose(bool disposing)
  895. {
  896. // don't do anything if the component is already disposed
  897. if (IsDisposed || !disposing) return;
  898. lock (lockObject)
  899. {
  900. IsDisposed = true;
  901. // de-register application event listener
  902. if (Application.Current != null)
  903. {
  904. Application.Current.Exit -= OnExit;
  905. }
  906. // stop timers
  907. singleClickTimer.Dispose();
  908. balloonCloseTimer.Dispose();
  909. // dispose message sink
  910. messageSink.Dispose();
  911. // remove icon
  912. RemoveTaskbarIcon();
  913. }
  914. }
  915. #endregion
  916. }
  917. }