diff --git a/CollapseLauncher/XAMLs/MainApp/TrayIcon.xaml b/CollapseLauncher/XAMLs/MainApp/TrayIcon.xaml
index bddd41b87..b9d5fbf21 100644
--- a/CollapseLauncher/XAMLs/MainApp/TrayIcon.xaml
+++ b/CollapseLauncher/XAMLs/MainApp/TrayIcon.xaml
@@ -7,24 +7,9 @@
mc:Ignorable="d">
-
-
-
-
-
-
-
-
-
+ MenuActivation="None"
+ Visibility="Collapsed" />
diff --git a/CollapseLauncher/XAMLs/MainApp/TrayIcon.xaml.cs b/CollapseLauncher/XAMLs/MainApp/TrayIcon.xaml.cs
index d650a09a0..a257c4a86 100644
--- a/CollapseLauncher/XAMLs/MainApp/TrayIcon.xaml.cs
+++ b/CollapseLauncher/XAMLs/MainApp/TrayIcon.xaml.cs
@@ -9,6 +9,7 @@
using Hi3Helper.Win32.Native.LibraryImport;
using Microsoft.Extensions.Logging;
using Microsoft.UI.Xaml;
+using Microsoft.UI.Xaml.Controls;
using Microsoft.Win32;
using System;
using System.Drawing;
@@ -24,6 +25,14 @@ public sealed partial class TrayIcon
{
internal static TrayIcon Current { get; private set; }
+ private const string HideWindowGlyph = "\uE949"; // CalculatorSubtract
+ private const string ShowWindowGlyph = "\uE744"; // ResizeMouseMedium
+
+ private TrayMenuHost _menuHost;
+ private MenuFlyoutItem _mainToggle;
+ private MenuFlyoutItem _consoleToggle;
+ private MenuFlyoutItem _exitItem;
+
internal bool IsCreated
{
get
@@ -114,35 +123,77 @@ private void Initializer(int instanceCount)
CollapseTaskbar.SetValue(TaskbarIcon.CustomNameProperty, $"Collapse Launcher{instanceIndicator}");
}
- // Bug in W10: Weird border issue
- // Verdict: disable SecondWindow ContextMenuMode, use classic.
- // if (isPreview) CollapseTaskbar.ContextMenuMode = ContextMenuMode.SecondWindow;
-#if DEBUG
CollapseTaskbar.ToolTipText =
- $"Collapse Launcher{instanceIndicator}\r\n" +
- $"{_popupHelp1}\r\n" +
- $"{_popupHelp2}";
-#else
- CollapseTaskbar.ToolTipText =
$"Collapse Launcher{instanceIndicator}\r\n" +
$"{_popupHelp1}\r\n" +
$"{_popupHelp2}";
-#endif
- CloseButton.Text = _exitApp;
- // Switch toggle text to see if it's started with Start
- MainTaskbarToggle.Text = (m_appMode == AppMode.StartOnTray) ? _showApp : _hideApp;
- ConsoleTaskbarToggle.Text = (m_appMode == AppMode.StartOnTray) ? _showConsole : _hideConsole;
+ MessageWindow messageWindow = CollapseTaskbar.TrayIcon.MessageWindow;
+ messageWindow.KeyboardEventReceived += OnTrayContextMenu;
CollapseTaskbar.Icon = Icon.FromHandle(LauncherConfig.AppIconSmall);
CollapseTaskbar.Visibility = Visibility.Visible;
- CollapseTaskbar.TrayIcon.MessageWindow.BalloonToolTipChanged += BalloonChangedEvent;
+ messageWindow.BalloonToolTipChanged += BalloonChangedEvent;
}
public void Dispose()
{
- CollapseTaskbar.Dispose();
+ CollapseTaskbar.TrayIcon.MessageWindow.KeyboardEventReceived -= OnTrayContextMenu;
+ TrayMenuHost host = _menuHost;
+ _menuHost = null;
+ try
+ {
+ host?.Dispose();
+ }
+ finally
+ {
+ CollapseTaskbar.Dispose();
+ }
+ }
+
+ private async void OnTrayContextMenu(object sender, MessageWindow.KeyboardEventReceivedEventArgs args)
+ {
+ if (args.KeyboardEvent != KeyboardEvent.ContextMenu || !CollapseTaskbar.IsCreated) return;
+
+ // H.NotifyIcon exposes the packed screen coordinates as unsigned words.
+ Point point = new((short)args.Point.X, (short)args.Point.Y);
+ TrayMenuHost host = _menuHost;
+ try
+ {
+ // The WinUI menu must acquire its XamlRoot from the tray host.
+ host = _menuHost ??= new TrayMenuHost(CreateTrayMenu(), CollapseTaskbar.TrayIcon, UpdateContextMenu);
+ await host.ShowAsync(point, ActualTheme, FlowDirection);
+ }
+ catch (Exception ex)
+ {
+ if (_menuHost != host) return;
+ _menuHost = null;
+ try
+ {
+ host?.Dispose();
+ }
+ catch (Exception cleanupException)
+ {
+ ex = new AggregateException(ex, cleanupException);
+ }
+ Logger.WriteLine($"[TrayIcon] Could not open the tray menu.\r\n{ex}", LogType.Warning, true);
+ }
+ }
+
+ private MenuFlyout CreateTrayMenu()
+ {
+ _mainToggle = CreateItem(ToggleMainVisibilityButtonCommand, HideWindowGlyph);
+ _consoleToggle = CreateItem(ToggleConsoleVisibilityButtonCommand, "\uE756"); // CommandPrompt
+ _exitItem = CreateItem(CloseAppCommand, "\uE7E8"); // PowerButton
+ return new MenuFlyout { Items = { _mainToggle, _consoleToggle, new MenuFlyoutSeparator(), _exitItem } };
+
+ MenuFlyoutItem CreateItem(IRelayCommand command, string glyph) => new()
+ {
+ Command = command,
+ Padding = new Thickness(11, 4, 11, 7), // Match the template's NarrowPadding state.
+ Icon = new FontIcon { Glyph = glyph }
+ };
}
///
@@ -235,12 +286,6 @@ private async void NotificationOnMouseEventReceived(object o, MessageWindow.Mous
[RelayCommand]
private void BringToForegroundInvoke() => BringToForeground();
- ///
- /// Update tray context menu
- ///
- [RelayCommand]
- private void UpdateContextMenuInvoke() => UpdateContextMenu();
-
///
/// Close app
///
@@ -262,14 +307,12 @@ public void ToggleConsoleVisibility(bool forceShow = false)
if (PInvoke.IsWindowVisible(consoleWindowHandle) && !forceShow)
{
LoggerConsole.DisposeConsole();
- ConsoleTaskbarToggle.Text = _showConsole;
Logger.WriteLine("Console is hidden!");
}
else
{
LoggerConsole.AllocateConsole();
PInvoke.SetForegroundWindow(PInvoke.GetConsoleWindow());
- ConsoleTaskbarToggle.Text = _hideConsole;
Logger.WriteLine("Console is visible!");
}
}
@@ -287,7 +330,6 @@ public void ToggleMainVisibility(bool forceShow = false)
{
WindowUtility.CurrentWindow?.Hide(false);
EfficiencyModeWrapper(true);
- MainTaskbarToggle.Text = _showApp;
// Increase refresh rate to 1000ms when main window is hidden
RefreshRate = RefreshRateSlow;
m_homePage?.StopCarouselSlideshow();
@@ -304,7 +346,6 @@ public void ToggleMainVisibility(bool forceShow = false)
WindowUtility.CurrentWindow?.Show(false);
EfficiencyModeWrapper(false);
PInvoke.SetForegroundWindow(mainWindowHandle);
- MainTaskbarToggle.Text = _hideApp;
m_homePage?.StartCarouselSlideshow();
// Revert refresh rate to its default
RefreshRate = RefreshRateDefault;
@@ -374,27 +415,17 @@ public void BringToForeground()
// ReSharper disable once MemberCanBePrivate.Global
public void UpdateContextMenu()
{
- if (!IsCreated) return;
- // Enable visibility toggle for console if the console is enabled
- if (LauncherConfig.GetAppConfigValue("EnableConsole").ToBool())
- {
- ConsoleTaskbarToggle.IsEnabled = true;
- }
- else
- {
- ConsoleTaskbarToggle.IsEnabled = false;
- ConsoleTaskbarToggle.Text = _hideConsole;
- }
-
- // Force refresh all text based on their respective window state
- nint consoleWindowHandle = PInvoke.GetConsoleWindow();
- nint mainWindowHandle = WindowUtility.CurrentWindowPtr;
-
- bool isMainWindowVisible = PInvoke.IsWindowVisible(mainWindowHandle);
- bool isConsoleVisible = LauncherConfig.GetAppConfigValue("EnableConsole").ToBool() && PInvoke.IsWindowVisible(consoleWindowHandle);
+ if (!IsCreated || _mainToggle is null) return;
+
+ bool consoleEnabled = LauncherConfig.GetAppConfigValue("EnableConsole").ToBool();
+ bool isConsoleVisible = consoleEnabled && PInvoke.IsWindowVisible(PInvoke.GetConsoleWindow());
+ bool isMainWindowVisible = PInvoke.IsWindowVisible(WindowUtility.CurrentWindowPtr);
- ConsoleTaskbarToggle.Text = isConsoleVisible ? _hideConsole : _showConsole;
- MainTaskbarToggle.Text = isMainWindowVisible ? _hideApp : _showApp;
+ _exitItem.Text = _exitApp;
+ _consoleToggle.IsEnabled = consoleEnabled;
+ _consoleToggle.Text = isConsoleVisible ? _hideConsole : _showConsole;
+ _mainToggle.Text = isMainWindowVisible ? _hideApp : _showApp;
+ ((FontIcon)_mainToggle.Icon).Glyph = isMainWindowVisible ? HideWindowGlyph : ShowWindowGlyph;
}
///
diff --git a/CollapseLauncher/XAMLs/MainApp/TrayMenuHost.cs b/CollapseLauncher/XAMLs/MainApp/TrayMenuHost.cs
new file mode 100644
index 000000000..8b9448f10
--- /dev/null
+++ b/CollapseLauncher/XAMLs/MainApp/TrayMenuHost.cs
@@ -0,0 +1,197 @@
+using Hi3Helper.Log;
+using Hi3Helper.Win32.Native.Enums;
+using Hi3Helper.Win32.Native.LibraryImport;
+using Microsoft.UI.Windowing;
+using Microsoft.UI.Xaml;
+using Microsoft.UI.Xaml.Controls;
+using Microsoft.UI.Xaml.Controls.Primitives;
+using System;
+using System.ComponentModel;
+using System.Drawing;
+using System.Runtime.InteropServices;
+using System.Threading.Tasks;
+using Windows.Graphics;
+using WinRT.Interop;
+using NativeRect = Hi3Helper.Win32.Native.Structs.Rect;
+using ShellTrayIcon = H.NotifyIcon.Core.TrayIcon;
+
+#nullable enable
+
+namespace CollapseLauncher;
+
+internal sealed partial class TrayMenuHost(MenuFlyout menu, ShellTrayIcon icon, Action updateMenu) : IDisposable
+{
+ private Window? _window;
+ private nint _handle;
+ private TaskCompletionSource? _anchorReady;
+
+ internal async ValueTask ShowAsync(Point point, ElementTheme theme, FlowDirection flowDirection)
+ {
+ if (menu.IsOpen || _anchorReady is not null) return;
+
+ Window window = _window ?? CreateWindow();
+ var anchor = (FrameworkElement)window.Content;
+ anchor.RequestedTheme = theme;
+ anchor.FlowDirection = flowDirection;
+
+ NativeRect rect = GetAnchorRect(icon.Id, point);
+ // Only the windowed flyout should occupy screen space.
+ if (!PInvoke.SetWindowPos(_handle, 0, rect.X, rect.Y, 0, 0,
+ SWP_FLAGS.SWP_NOZORDER | SWP_FLAGS.SWP_NOACTIVATE | SWP_FLAGS.SWP_NOSENDCHANGING))
+ throw new InvalidOperationException("Could not position the tray menu anchor.");
+
+ window.Activate();
+ if (PInvoke.GetForegroundWindow() != _handle)
+ PInvoke.SetForegroundWindow(_handle);
+
+ XamlRoot? root = anchor.XamlRoot;
+ if (root is null)
+ {
+ _anchorReady = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ anchor.Loaded += OnAnchorLoaded;
+ try
+ {
+ root = await _anchorReady.Task.WaitAsync(TimeSpan.FromSeconds(1));
+ }
+ finally
+ {
+ anchor.Loaded -= OnAnchorLoaded;
+ _anchorReady = null;
+ }
+ }
+
+ if (_window != window) return;
+ double? scale = IsInWorkArea(rect) ? root.RasterizationScale : null;
+ updateMenu();
+ menu.ShowAt(anchor, new FlyoutShowOptions
+ {
+ Position = new Windows.Foundation.Point(0, 0),
+ ExclusionRect = scale is { } factor
+ ? new Windows.Foundation.Rect(0, 0, rect.Width / factor, rect.Height / factor)
+ : null,
+ ShowMode = FlyoutShowMode.Standard
+ });
+ if (!menu.IsOpen)
+ throw new InvalidOperationException("The tray menu did not open.");
+ }
+
+ private void OnAnchorLoaded(object sender, RoutedEventArgs args)
+ {
+ if (((FrameworkElement)sender).XamlRoot is { } root)
+ _anchorReady?.TrySetResult(root);
+ }
+
+ private Window CreateWindow()
+ {
+ var window = new Window();
+ _window = window;
+ _handle = WindowNative.GetWindowHandle(window);
+ window.Content = new Grid();
+
+ ((OverlappedPresenter)window.AppWindow.Presenter).IsAlwaysOnTop = true;
+ HideWindowInTaskbar(_handle);
+
+ // A popup host has no non-client frame, including on Windows 10.
+ WS_STYLE style = PInvoke.GetWindowLong(_handle, GWL_INDEX.GWL_STYLE);
+ if (PInvoke.SetWindowLong(_handle, GWL_INDEX.GWL_STYLE,
+ (style & ~WS_STYLE.WS_OVERLAPPEDWINDOW) | WS_STYLE.WS_POPUP) == 0 &&
+ Marshal.GetLastPInvokeError() != 0)
+ throw new Win32Exception(Marshal.GetLastPInvokeError());
+ if (!PInvoke.SetWindowPos(_handle, 0, 0, 0, 0, 0,
+ SWP_FLAGS.SWP_FRAMECHANGED | SWP_FLAGS.SWP_NOMOVE |
+ SWP_FLAGS.SWP_NOZORDER | SWP_FLAGS.SWP_NOACTIVATE))
+ throw new Win32Exception(Marshal.GetLastPInvokeError());
+
+ menu.ShouldConstrainToRootBounds = false;
+ menu.Closed += OnMenuClosed;
+ window.Activated += OnWindowActivated;
+ return window;
+ }
+
+ private void OnWindowActivated(object sender, WindowActivatedEventArgs args)
+ {
+ if (args.WindowActivationState == WindowActivationState.Deactivated && menu.IsOpen && sender is Window window)
+ window.DispatcherQueue.TryEnqueue(() =>
+ {
+ if (_window == window && PInvoke.GetForegroundWindow() != _handle)
+ menu.Hide();
+ });
+ }
+
+ private void OnMenuClosed(object? sender, object args)
+ {
+ bool returnFocus = PInvoke.GetForegroundWindow() == _handle;
+ _window?.AppWindow.Hide();
+ if (!returnFocus || !icon.IsCreated) return;
+
+ try
+ {
+ icon.SetFocus();
+ }
+ catch (InvalidOperationException ex)
+ {
+ Logger.WriteLine($"[TrayIcon] Could not return focus to the notification area. {ex.Message}", LogType.Warning, true);
+ }
+ }
+
+ public void Dispose()
+ {
+ if (_window is not { } window) return;
+
+ _window = null;
+ _anchorReady?.TrySetCanceled();
+ menu.Closed -= OnMenuClosed;
+ window.Activated -= OnWindowActivated;
+ window.Close();
+ }
+
+ private static void HideWindowInTaskbar(nint hwnd)
+ {
+ // TODO: Add WS_EX_STYLE to Hi3Helper.Win32 module
+ WS_STYLE style = PInvoke.GetWindowLong(hwnd, GWL_INDEX.GWL_EXSTYLE);
+ style |= (WS_STYLE)0x00000080; // WS_EX_TOOLWINDOW
+ style &= ~(WS_STYLE)0x00040000; // WS_EX_APPWINDOW
+
+ _ = PInvoke.SetWindowLong(hwnd, GWL_INDEX.GWL_EXSTYLE, style);
+ }
+
+ private static unsafe NativeRect GetAnchorRect(Guid id, Point point)
+ {
+ var identifier = new NotifyIconIdentifier(id);
+ NativeRect rect;
+ return Shell_NotifyIconGetRect(ref identifier, &rect) == 0 && rect.Width > 0 && rect.Height > 0
+ ? rect
+ : NativeRect.FromXYWH(point.X, point.Y, 0, 0);
+ }
+
+ private static bool IsInWorkArea(NativeRect rect)
+ {
+ if (rect.Width <= 0 || rect.Height <= 0) return false;
+
+ // WinUI already flips a point anchored outside the work area back inside.
+ var display = DisplayArea.GetFromPoint(new PointInt32(rect.X, rect.Y), DisplayAreaFallback.Nearest);
+ RectInt32 workArea = display.WorkArea;
+ int x = rect.X - workArea.X;
+ int y = rect.Y - workArea.Y;
+ return x >= 0 && x + rect.Width <= workArea.Width && y >= 0 && y + rect.Height <= workArea.Height;
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ private readonly struct NotifyIconIdentifier
+ {
+ private readonly uint _size;
+ private readonly nint _windowHandle;
+ private readonly uint _id;
+ private readonly Guid _guid;
+
+ internal unsafe NotifyIconIdentifier(Guid guid)
+ {
+ _size = (uint)sizeof(NotifyIconIdentifier);
+ _guid = guid;
+ }
+ }
+
+ [LibraryImport("shell32.dll")]
+ [DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
+ private static unsafe partial int Shell_NotifyIconGetRect(ref readonly NotifyIconIdentifier identifier, NativeRect* rect);
+}