NotifyIcon.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Linq;
  5. using System.Runtime.InteropServices;
  6. using System.Windows;
  7. using System.Windows.Controls;
  8. using System.Windows.Controls.Primitives;
  9. using System.Windows.Data;
  10. using System.Windows.Input;
  11. using System.Windows.Media;
  12. using System.Windows.Threading;
  13. using HandyControl.Data;
  14. using HandyControl.Tools;
  15. using HandyControl.Tools.Interop;
  16. namespace HandyControl.Controls;
  17. public class NotifyIcon : FrameworkElement, IDisposable
  18. {
  19. private bool _isMouseOver;
  20. private bool _added;
  21. private readonly object _syncObj = new();
  22. private readonly int _id;
  23. private ImageSource _icon;
  24. private IntPtr _iconCurrentHandle;
  25. private IntPtr _iconDefaultHandle;
  26. private IconHandle _iconHandle;
  27. private const int WmTrayMouseMessage = InteropValues.WM_USER + 1024;
  28. private string _windowClassName;
  29. private int _wmTaskbarCreated;
  30. private IntPtr _messageWindowHandle;
  31. private readonly InteropValues.WndProc _callback;
  32. private Popup _contextContent;
  33. private bool _doubleClick;
  34. private DispatcherTimer _dispatcherTimerBlink;
  35. private DispatcherTimer _dispatcherTimerPos;
  36. private bool _isTransparent;
  37. private bool _isDisposed;
  38. private static int NextId;
  39. private static readonly Dictionary<string, NotifyIcon> NotifyIconDic = new();
  40. static NotifyIcon()
  41. {
  42. VisibilityProperty.OverrideMetadata(typeof(NotifyIcon), new PropertyMetadata(Visibility.Visible, OnVisibilityChanged));
  43. DataContextProperty.OverrideMetadata(typeof(NotifyIcon), new FrameworkPropertyMetadata(DataContextPropertyChanged));
  44. ContextMenuProperty.OverrideMetadata(typeof(NotifyIcon), new FrameworkPropertyMetadata(ContextMenuPropertyChanged));
  45. }
  46. private static void OnVisibilityChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  47. {
  48. var ctl = (NotifyIcon) d;
  49. var v = (Visibility) e.NewValue;
  50. if (v == Visibility.Visible)
  51. {
  52. if (ctl._iconCurrentHandle == IntPtr.Zero)
  53. {
  54. ctl.OnIconChanged();
  55. }
  56. ctl.UpdateIcon(true);
  57. }
  58. else if (ctl._iconCurrentHandle != IntPtr.Zero)
  59. {
  60. ctl.UpdateIcon(false);
  61. }
  62. }
  63. private static void DataContextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) =>
  64. ((NotifyIcon) d).OnDataContextPropertyChanged(e);
  65. private void OnDataContextPropertyChanged(DependencyPropertyChangedEventArgs e)
  66. {
  67. UpdateDataContext(_contextContent, e.OldValue, e.NewValue);
  68. UpdateDataContext(ContextMenu, e.OldValue, e.NewValue);
  69. }
  70. private static void ContextMenuPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  71. {
  72. var ctl = (NotifyIcon) d;
  73. ctl.OnContextMenuPropertyChanged(e);
  74. }
  75. private void OnContextMenuPropertyChanged(DependencyPropertyChangedEventArgs e) =>
  76. UpdateDataContext((ContextMenu) e.NewValue, null, DataContext);
  77. public NotifyIcon()
  78. {
  79. _id = ++NextId;
  80. _callback = Callback;
  81. Loaded += (s, e) => Init();
  82. if (Application.Current != null) Application.Current.Exit += (s, e) => Dispose();
  83. }
  84. ~NotifyIcon() => Dispose(false);
  85. public void Init()
  86. {
  87. RegisterClass();
  88. if (Visibility == Visibility.Visible)
  89. {
  90. OnIconChanged();
  91. UpdateIcon(true);
  92. }
  93. _dispatcherTimerPos = new DispatcherTimer
  94. {
  95. Interval = TimeSpan.FromMilliseconds(200)
  96. };
  97. _dispatcherTimerPos.Tick += DispatcherTimerPos_Tick;
  98. }
  99. public static void Register(string token, NotifyIcon notifyIcon)
  100. {
  101. if (string.IsNullOrEmpty(token) || notifyIcon == null) return;
  102. NotifyIconDic[token] = notifyIcon;
  103. }
  104. public static void Unregister(string token, NotifyIcon notifyIcon)
  105. {
  106. if (string.IsNullOrEmpty(token) || notifyIcon == null) return;
  107. if (NotifyIconDic.ContainsKey(token))
  108. {
  109. if (ReferenceEquals(NotifyIconDic[token], notifyIcon))
  110. {
  111. NotifyIconDic.Remove(token);
  112. }
  113. }
  114. }
  115. public static void Unregister(NotifyIcon notifyIcon)
  116. {
  117. if (notifyIcon == null) return;
  118. var first = NotifyIconDic.FirstOrDefault(item => ReferenceEquals(notifyIcon, item.Value));
  119. if (!string.IsNullOrEmpty(first.Key))
  120. {
  121. NotifyIconDic.Remove(first.Key);
  122. }
  123. }
  124. public static void Unregister(string token)
  125. {
  126. if (string.IsNullOrEmpty(token)) return;
  127. if (NotifyIconDic.ContainsKey(token))
  128. {
  129. NotifyIconDic.Remove(token);
  130. }
  131. }
  132. public static void ShowBalloonTip(string title, string content, NotifyIconInfoType infoType, string token)
  133. {
  134. if (NotifyIconDic.TryGetValue(token, out var notifyIcon))
  135. {
  136. notifyIcon.ShowBalloonTip(title, content, infoType);
  137. }
  138. }
  139. public void ShowBalloonTip(string title, string content, NotifyIconInfoType infoType)
  140. {
  141. if (!_added || DesignerHelper.IsInDesignMode) return;
  142. var data = new InteropValues.NOTIFYICONDATA
  143. {
  144. uFlags = InteropValues.NIF_INFO,
  145. hWnd = _messageWindowHandle,
  146. uID = _id,
  147. szInfoTitle = title ?? string.Empty,
  148. szInfo = content ?? string.Empty
  149. };
  150. data.dwInfoFlags = infoType switch
  151. {
  152. NotifyIconInfoType.Info => InteropValues.NIIF_INFO,
  153. NotifyIconInfoType.Warning => InteropValues.NIIF_WARNING,
  154. NotifyIconInfoType.Error => InteropValues.NIIF_ERROR,
  155. NotifyIconInfoType.None => InteropValues.NIIF_NONE,
  156. _ => data.dwInfoFlags
  157. };
  158. InteropMethods.Shell_NotifyIcon(InteropValues.NIM_MODIFY, data);
  159. }
  160. public void Dispose()
  161. {
  162. Dispose(true);
  163. GC.SuppressFinalize(this);
  164. }
  165. public void CloseContextControl()
  166. {
  167. if (_contextContent != null)
  168. {
  169. _contextContent.IsOpen = false;
  170. }
  171. else if (ContextMenu != null)
  172. {
  173. ContextMenu.IsOpen = false;
  174. }
  175. }
  176. public static readonly DependencyProperty TokenProperty = DependencyProperty.Register(
  177. nameof(Token), typeof(string), typeof(NotifyIcon), new PropertyMetadata(default(string), OnTokenChanged));
  178. private static void OnTokenChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  179. {
  180. if (d is NotifyIcon notifyIcon)
  181. {
  182. if (e.NewValue == null)
  183. {
  184. Unregister(notifyIcon);
  185. }
  186. else
  187. {
  188. Register(e.NewValue.ToString(), notifyIcon);
  189. }
  190. }
  191. }
  192. public string Token
  193. {
  194. get => (string) GetValue(TokenProperty);
  195. set => SetValue(TokenProperty, value);
  196. }
  197. public static readonly DependencyProperty TextProperty = DependencyProperty.Register(
  198. nameof(Text), typeof(string), typeof(NotifyIcon), new PropertyMetadata(default(string)));
  199. public string Text
  200. {
  201. get => (string) GetValue(TextProperty);
  202. set => SetValue(TextProperty, value);
  203. }
  204. public static readonly DependencyProperty IconProperty = DependencyProperty.Register(
  205. nameof(Icon), typeof(ImageSource), typeof(NotifyIcon), new PropertyMetadata(default(ImageSource), OnIconChanged));
  206. private static void OnIconChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  207. {
  208. var ctl = (NotifyIcon) d;
  209. ctl._icon = (ImageSource) e.NewValue;
  210. ctl.OnIconChanged();
  211. if (!string.IsNullOrEmpty(ctl._windowClassName) && !ctl.IsBlink && ctl.Visibility == Visibility.Visible)
  212. {
  213. ctl.UpdateIcon(true);
  214. }
  215. }
  216. public ImageSource Icon
  217. {
  218. get => (ImageSource) GetValue(IconProperty);
  219. set => SetValue(IconProperty, value);
  220. }
  221. public static readonly DependencyProperty ContextContentProperty = DependencyProperty.Register(
  222. nameof(ContextContent), typeof(object), typeof(NotifyIcon), new PropertyMetadata(default(object)));
  223. public object ContextContent
  224. {
  225. get => GetValue(ContextContentProperty);
  226. set => SetValue(ContextContentProperty, value);
  227. }
  228. public static readonly DependencyProperty BlinkIntervalProperty = DependencyProperty.Register(
  229. nameof(BlinkInterval), typeof(TimeSpan), typeof(NotifyIcon), new PropertyMetadata(TimeSpan.FromMilliseconds(500), OnBlinkIntervalChanged));
  230. private static void OnBlinkIntervalChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  231. {
  232. var ctl = (NotifyIcon) d;
  233. if (ctl._dispatcherTimerBlink != null)
  234. {
  235. ctl._dispatcherTimerBlink.Interval = (TimeSpan) e.NewValue;
  236. }
  237. }
  238. public TimeSpan BlinkInterval
  239. {
  240. get => (TimeSpan) GetValue(BlinkIntervalProperty);
  241. set => SetValue(BlinkIntervalProperty, value);
  242. }
  243. public static readonly DependencyProperty IsBlinkProperty = DependencyProperty.Register(
  244. nameof(IsBlink), typeof(bool), typeof(NotifyIcon), new PropertyMetadata(ValueBoxes.FalseBox, OnIsBlinkChanged));
  245. private static void OnIsBlinkChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  246. {
  247. var ctl = (NotifyIcon) d;
  248. if (ctl.Visibility != Visibility.Visible) return;
  249. if ((bool) e.NewValue)
  250. {
  251. if (ctl._dispatcherTimerBlink == null)
  252. {
  253. ctl._dispatcherTimerBlink = new DispatcherTimer
  254. {
  255. Interval = ctl.BlinkInterval
  256. };
  257. ctl._dispatcherTimerBlink.Tick += ctl.DispatcherTimerBlinkTick;
  258. }
  259. ctl._dispatcherTimerBlink.Start();
  260. }
  261. else
  262. {
  263. ctl._dispatcherTimerBlink?.Stop();
  264. ctl._dispatcherTimerBlink = null;
  265. ctl.UpdateIcon(true);
  266. }
  267. }
  268. public bool IsBlink
  269. {
  270. get => (bool) GetValue(IsBlinkProperty);
  271. set => SetValue(IsBlinkProperty, ValueBoxes.BooleanBox(value));
  272. }
  273. private void DispatcherTimerBlinkTick(object sender, EventArgs e)
  274. {
  275. if (Visibility != Visibility.Visible || _iconCurrentHandle == IntPtr.Zero) return;
  276. UpdateIcon(true, !_isTransparent);
  277. }
  278. private bool CheckMouseIsEnter()
  279. {
  280. var isTrue = FindNotifyIcon(out var rectNotifyList);
  281. if (!isTrue) return false;
  282. InteropMethods.GetCursorPos(out var point);
  283. return rectNotifyList.Any(rectNotify =>
  284. point.X >= rectNotify.Left &&
  285. point.X <= rectNotify.Right &&
  286. point.Y >= rectNotify.Top &&
  287. point.Y <= rectNotify.Bottom);
  288. }
  289. private void DispatcherTimerPos_Tick(object sender, EventArgs e)
  290. {
  291. if (CheckMouseIsEnter())
  292. {
  293. if (!_isMouseOver)
  294. {
  295. _isMouseOver = true;
  296. RaiseEvent(new MouseEventArgs(Mouse.PrimaryDevice, Environment.TickCount)
  297. {
  298. RoutedEvent = MouseEnterEvent
  299. });
  300. _dispatcherTimerPos.Interval = TimeSpan.FromMilliseconds(500);
  301. }
  302. }
  303. else
  304. {
  305. _dispatcherTimerPos.Stop();
  306. _isMouseOver = false;
  307. RaiseEvent(new MouseEventArgs(Mouse.PrimaryDevice, Environment.TickCount)
  308. {
  309. RoutedEvent = MouseLeaveEvent
  310. });
  311. }
  312. }
  313. //referenced from http://www.cnblogs.com/sczmzx/p/5158127.html
  314. private IntPtr FindTrayToolbarWindow()
  315. {
  316. var hWnd = InteropMethods.FindWindow("Shell_TrayWnd", null);
  317. if (hWnd != IntPtr.Zero)
  318. {
  319. hWnd = InteropMethods.FindWindowEx(hWnd, IntPtr.Zero, "TrayNotifyWnd", null);
  320. if (hWnd != IntPtr.Zero)
  321. {
  322. hWnd = InteropMethods.FindWindowEx(hWnd, IntPtr.Zero, "SysPager", null);
  323. if (hWnd != IntPtr.Zero)
  324. {
  325. hWnd = InteropMethods.FindWindowEx(hWnd, IntPtr.Zero, "ToolbarWindow32", null);
  326. }
  327. }
  328. }
  329. return hWnd;
  330. }
  331. //referenced from http://www.cnblogs.com/sczmzx/p/5158127.html
  332. private IntPtr FindTrayToolbarOverFlowWindow()
  333. {
  334. var hWnd = InteropMethods.FindWindow("NotifyIconOverflowWindow", null);
  335. if (hWnd != IntPtr.Zero)
  336. {
  337. hWnd = InteropMethods.FindWindowEx(hWnd, IntPtr.Zero, "ToolbarWindow32", null);
  338. }
  339. return hWnd;
  340. }
  341. private bool FindNotifyIcon(out List<InteropValues.RECT> rectList)
  342. {
  343. var rectNotifyList = new List<InteropValues.RECT>();
  344. var hTrayWnd = FindTrayToolbarWindow();
  345. var isTrue = FindNotifyIcon(hTrayWnd, ref rectNotifyList);
  346. if (!isTrue)
  347. {
  348. hTrayWnd = FindTrayToolbarOverFlowWindow();
  349. isTrue = FindNotifyIcon(hTrayWnd, ref rectNotifyList);
  350. }
  351. rectList = rectNotifyList;
  352. return isTrue;
  353. }
  354. //referenced from http://www.cnblogs.com/sczmzx/p/5158127.html
  355. private bool FindNotifyIcon(IntPtr hTrayWnd, ref List<InteropValues.RECT> rectNotifyList)
  356. {
  357. InteropMethods.GetWindowRect(hTrayWnd, out var rectTray);
  358. var count = (int) InteropMethods.SendMessage(hTrayWnd, InteropValues.TB_BUTTONCOUNT, 0, IntPtr.Zero);
  359. var isFind = false;
  360. if (count > 0)
  361. {
  362. InteropMethods.GetWindowThreadProcessId(hTrayWnd, out var trayPid);
  363. var hProcess = InteropMethods.OpenProcess(InteropValues.ProcessAccess.VMOperation | InteropValues.ProcessAccess.VMRead | InteropValues.ProcessAccess.VMWrite, false, trayPid);
  364. var address = InteropMethods.VirtualAllocEx(hProcess, IntPtr.Zero, 1024, InteropValues.AllocationType.Commit, InteropValues.MemoryProtection.ReadWrite);
  365. var btnData = new InteropValues.TBBUTTON();
  366. var trayData = new InteropValues.TRAYDATA();
  367. var handle = Process.GetCurrentProcess().Id;
  368. for (uint i = 0; i < count; i++)
  369. {
  370. InteropMethods.SendMessage(hTrayWnd, InteropValues.TB_GETBUTTON, i, address);
  371. var isTrue = InteropMethods.ReadProcessMemory(hProcess, address, out btnData, Marshal.SizeOf(btnData), out _);
  372. if (!isTrue) continue;
  373. if (btnData.dwData == IntPtr.Zero)
  374. {
  375. btnData.dwData = btnData.iString;
  376. }
  377. InteropMethods.ReadProcessMemory(hProcess, btnData.dwData, out trayData, Marshal.SizeOf(trayData), out _);
  378. InteropMethods.GetWindowThreadProcessId(trayData.hwnd, out var dwProcessId);
  379. if (dwProcessId == (uint) handle)
  380. {
  381. var rect = new InteropValues.RECT();
  382. var lngRect = InteropMethods.VirtualAllocEx(hProcess, IntPtr.Zero, Marshal.SizeOf(typeof(Rect)), InteropValues.AllocationType.Commit, InteropValues.MemoryProtection.ReadWrite);
  383. InteropMethods.SendMessage(hTrayWnd, InteropValues.TB_GETITEMRECT, i, lngRect);
  384. InteropMethods.ReadProcessMemory(hProcess, lngRect, out rect, Marshal.SizeOf(rect), out _);
  385. InteropMethods.VirtualFreeEx(hProcess, lngRect, Marshal.SizeOf(rect), InteropValues.FreeType.Decommit);
  386. InteropMethods.VirtualFreeEx(hProcess, lngRect, 0, InteropValues.FreeType.Release);
  387. var left = rectTray.Left + rect.Left;
  388. var top = rectTray.Top + rect.Top;
  389. var botton = rectTray.Top + rect.Bottom;
  390. var right = rectTray.Left + rect.Right;
  391. rectNotifyList.Add(new InteropValues.RECT
  392. {
  393. Left = left,
  394. Right = right,
  395. Top = top,
  396. Bottom = botton
  397. });
  398. isFind = true;
  399. }
  400. }
  401. InteropMethods.VirtualFreeEx(hProcess, address, 0x4096, InteropValues.FreeType.Decommit);
  402. InteropMethods.VirtualFreeEx(hProcess, address, 0, InteropValues.FreeType.Release);
  403. InteropMethods.CloseHandle(hProcess);
  404. }
  405. return isFind;
  406. }
  407. private void OnIconChanged()
  408. {
  409. if (_windowClassName == null) return;
  410. if (_icon != null)
  411. {
  412. IconHelper.GetIconHandlesFromImageSource(_icon, out _, out _iconHandle);
  413. _iconCurrentHandle = _iconHandle.CriticalGetHandle();
  414. }
  415. else
  416. {
  417. if (_iconDefaultHandle == IntPtr.Zero)
  418. {
  419. IconHelper.GetDefaultIconHandles(out _, out _iconHandle);
  420. _iconDefaultHandle = _iconHandle.CriticalGetHandle();
  421. }
  422. _iconCurrentHandle = _iconDefaultHandle;
  423. }
  424. }
  425. private void UpdateIcon(bool showIconInTray, bool isTransparent = false)
  426. {
  427. lock (_syncObj)
  428. {
  429. if (DesignerHelper.IsInDesignMode) return;
  430. _isTransparent = isTransparent;
  431. var data = new InteropValues.NOTIFYICONDATA
  432. {
  433. uCallbackMessage = WmTrayMouseMessage,
  434. uFlags = InteropValues.NIF_MESSAGE | InteropValues.NIF_ICON | InteropValues.NIF_TIP,
  435. hWnd = _messageWindowHandle,
  436. uID = _id,
  437. dwInfoFlags = InteropValues.NIF_TIP,
  438. hIcon = isTransparent ? IntPtr.Zero : _iconCurrentHandle,
  439. szTip = Text
  440. };
  441. if (showIconInTray)
  442. {
  443. if (!_added)
  444. {
  445. InteropMethods.Shell_NotifyIcon(InteropValues.NIM_ADD, data);
  446. _added = true;
  447. }
  448. else
  449. {
  450. InteropMethods.Shell_NotifyIcon(InteropValues.NIM_MODIFY, data);
  451. }
  452. }
  453. else if (_added)
  454. {
  455. InteropMethods.Shell_NotifyIcon(InteropValues.NIM_DELETE, data);
  456. _added = false;
  457. }
  458. }
  459. }
  460. private void RegisterClass()
  461. {
  462. _windowClassName = $"HandyControl.Controls.NotifyIcon{Guid.NewGuid()}";
  463. var wndclass = new InteropValues.WNDCLASS4ICON
  464. {
  465. style = 0,
  466. lpfnWndProc = _callback,
  467. cbClsExtra = 0,
  468. cbWndExtra = 0,
  469. hInstance = IntPtr.Zero,
  470. hIcon = IntPtr.Zero,
  471. hCursor = IntPtr.Zero,
  472. hbrBackground = IntPtr.Zero,
  473. lpszMenuName = "",
  474. lpszClassName = _windowClassName
  475. };
  476. InteropMethods.RegisterClass(wndclass);
  477. _wmTaskbarCreated = InteropMethods.RegisterWindowMessage("TaskbarCreated");
  478. _messageWindowHandle = InteropMethods.CreateWindowEx(0, _windowClassName, "", 0, 0, 0, 1, 1,
  479. IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
  480. }
  481. private IntPtr Callback(IntPtr hWnd, int msg, IntPtr wparam, IntPtr lparam)
  482. {
  483. if (msg == _wmTaskbarCreated)
  484. {
  485. if (_messageWindowHandle == hWnd && Visibility == Visibility.Visible)
  486. {
  487. UpdateIcon(false);
  488. UpdateIcon(true);
  489. }
  490. }
  491. else
  492. {
  493. switch (lparam.ToInt64())
  494. {
  495. case InteropValues.WM_LBUTTONDBLCLK:
  496. WmMouseDown(MouseButton.Left, 2);
  497. break;
  498. case InteropValues.WM_LBUTTONUP:
  499. WmMouseUp(MouseButton.Left);
  500. break;
  501. case InteropValues.WM_RBUTTONUP:
  502. ShowContextMenu();
  503. WmMouseUp(MouseButton.Right);
  504. break;
  505. case InteropValues.WM_MOUSEMOVE:
  506. if (!_dispatcherTimerPos.IsEnabled)
  507. {
  508. _dispatcherTimerPos.Interval = TimeSpan.FromMilliseconds(200);
  509. _dispatcherTimerPos.Start();
  510. }
  511. break;
  512. }
  513. }
  514. return InteropMethods.DefWindowProc(hWnd, msg, wparam, lparam);
  515. }
  516. private void WmMouseDown(MouseButton button, int clicks)
  517. {
  518. if (clicks == 2)
  519. {
  520. RaiseEvent(new MouseButtonEventArgs(Mouse.PrimaryDevice, Environment.TickCount, button)
  521. {
  522. RoutedEvent = MouseDoubleClickEvent
  523. });
  524. _doubleClick = true;
  525. }
  526. }
  527. private void WmMouseUp(MouseButton button)
  528. {
  529. if (!_doubleClick && button == MouseButton.Left)
  530. {
  531. RaiseEvent(new MouseButtonEventArgs(Mouse.PrimaryDevice, Environment.TickCount, button)
  532. {
  533. RoutedEvent = ClickEvent
  534. });
  535. }
  536. _doubleClick = false;
  537. }
  538. private void ShowContextMenu()
  539. {
  540. if (ContextContent != null)
  541. {
  542. _contextContent ??= new Popup
  543. {
  544. Placement = PlacementMode.Mouse,
  545. AllowsTransparency = true,
  546. StaysOpen = false,
  547. UseLayoutRounding = true,
  548. SnapsToDevicePixels = true
  549. };
  550. _contextContent.Child = new ContentControl
  551. {
  552. Content = ContextContent
  553. };
  554. _contextContent.IsOpen = true;
  555. InteropMethods.SetForegroundWindow(_contextContent.Child.GetHandle());
  556. }
  557. else if (ContextMenu != null)
  558. {
  559. if (ContextMenu.Items.Count == 0) return;
  560. ContextMenu.InvalidateProperty(StyleProperty);
  561. foreach (var item in ContextMenu.Items)
  562. {
  563. if (item is MenuItem menuItem)
  564. {
  565. menuItem.InvalidateProperty(StyleProperty);
  566. }
  567. else
  568. {
  569. var container = ContextMenu.ItemContainerGenerator.ContainerFromItem(item) as MenuItem;
  570. container?.InvalidateProperty(StyleProperty);
  571. }
  572. }
  573. ContextMenu.Placement = PlacementMode.Mouse;
  574. ContextMenu.IsOpen = true;
  575. InteropMethods.SetForegroundWindow(ContextMenu.GetHandle());
  576. }
  577. }
  578. public static readonly RoutedEvent ClickEvent =
  579. EventManager.RegisterRoutedEvent("Click", RoutingStrategy.Bubble,
  580. typeof(RoutedEventHandler), typeof(NotifyIcon));
  581. public event RoutedEventHandler Click
  582. {
  583. add => AddHandler(ClickEvent, value);
  584. remove => RemoveHandler(ClickEvent, value);
  585. }
  586. public static readonly RoutedEvent MouseDoubleClickEvent =
  587. EventManager.RegisterRoutedEvent("MouseDoubleClick", RoutingStrategy.Bubble,
  588. typeof(RoutedEventHandler), typeof(NotifyIcon));
  589. public event RoutedEventHandler MouseDoubleClick
  590. {
  591. add => AddHandler(MouseDoubleClickEvent, value);
  592. remove => RemoveHandler(MouseDoubleClickEvent, value);
  593. }
  594. private void UpdateDataContext(FrameworkElement target, object oldValue, object newValue)
  595. {
  596. if (target == null || BindingOperations.GetBindingExpression(target, DataContextProperty) != null) return;
  597. if (ReferenceEquals(this, target.DataContext) || Equals(oldValue, target.DataContext))
  598. {
  599. target.DataContext = newValue ?? this;
  600. }
  601. }
  602. private void Dispose(bool disposing)
  603. {
  604. if (_isDisposed) return;
  605. if (disposing)
  606. {
  607. if (_dispatcherTimerBlink != null && IsBlink)
  608. {
  609. _dispatcherTimerBlink.Stop();
  610. }
  611. UpdateIcon(false);
  612. }
  613. _isDisposed = true;
  614. }
  615. }