private void UpdateIcon(bool forceDestroy = false) { if (DesignerProperties.GetIsInDesignMode(this)) { return; } var iconVisibility = IconVisibility; bool showIconInTray = !forceDestroy && (iconVisibility == NotifyIconVisibility.Visible || (iconVisibility == NotifyIconVisibility.UseControlVisibility && IsVisible)); lock (_syncObj) { IntPtr iconHandle = IntPtr.Zero; try { _allWindowsPermission.Demand(); if (showIconInTray && _hwndSource == null) { _hwndSource = new NotifyIconHwndSource(this); } if (_hwndSource != null) { _hwndSource.LockReference(showIconInTray); var pnid = new NativeMethods.NOTIFYICONDATA { uCallbackMessage = (int)NativeMethods.WindowMessage.TrayMouseMessage, uFlags = NativeMethods.NotifyIconFlags.Message | NativeMethods.NotifyIconFlags.ToolTip, hWnd = _hwndSource.Handle, uID = _id, szTip = Text }; if (Icon != null) { iconHandle = NativeMethods.GetHIcon(Icon); pnid.uFlags |= NativeMethods.NotifyIconFlags.Icon; pnid.hIcon = iconHandle; } if (showIconInTray && iconHandle != IntPtr.Zero) { if (!_iconCreated) { NativeMethods.Shell_NotifyIcon(0, pnid); _iconCreated = true; } else { NativeMethods.Shell_NotifyIcon(1, pnid); } } else if (_iconCreated) { NativeMethods.Shell_NotifyIcon(2, pnid); _iconCreated = false; } } } finally { if (iconHandle != IntPtr.Zero) { NativeMethods.DestroyIcon(iconHandle); } } } }
private void UpdateIcon(bool forceDestroy = false) { if (DesignerProperties.GetIsInDesignMode(this)) return; var iconVisibility = IconVisibility; bool showIconInTray = !forceDestroy && (iconVisibility == NotifyIconVisibility.Visible || (iconVisibility == NotifyIconVisibility.UseControlVisibility && IsVisible)); lock (_syncObj) { IntPtr iconHandle = IntPtr.Zero; try { _allWindowsPermission.Demand(); if (showIconInTray && _hwndSource == null) { _hwndSource = new NotifyIconHwndSource(this); } if (_hwndSource != null) { _hwndSource.LockReference(showIconInTray); var pnid = new NativeMethods.NOTIFYICONDATA { uCallbackMessage = (int)NativeMethods.WindowMessage.TrayMouseMessage, uFlags = NativeMethods.NotifyIconFlags.Message | NativeMethods.NotifyIconFlags.ToolTip, hWnd = _hwndSource.Handle, uID = _id, szTip = Text }; if (Icon != null) { iconHandle = NativeMethods.GetHIcon(Icon); pnid.uFlags |= NativeMethods.NotifyIconFlags.Icon; pnid.hIcon = iconHandle; } if (showIconInTray && iconHandle != IntPtr.Zero) { if (!_iconCreated) { NativeMethods.Shell_NotifyIcon(0, pnid); _iconCreated = true; } else { NativeMethods.Shell_NotifyIcon(1, pnid); } } else if (_iconCreated) { NativeMethods.Shell_NotifyIcon(2, pnid); _iconCreated = false; } } } finally { if (iconHandle != IntPtr.Zero) { NativeMethods.DestroyIcon(iconHandle); } } } }