using System.Runtime.InteropServices; using Microsoft.UI.Composition.SystemBackdrops; using Microsoft.UI.Windowing; using Microsoft.UI.Xaml.Controls.Primitives; using Microsoft.UI.Xaml.Media; using Windows.Graphics; namespace XFEWorkflow.Controls; internal enum TrayCommand { Open, EmergencyStop, Resume, Exit } /// A dedicated anchor lets a native WinUI menu open while the main window stays hidden. public sealed partial class TrayMenuWindow : Window, IDisposable { private readonly FrameworkElement ownerRoot; private bool pending, active, closing, disposed; private PointInt32 requestedPoint; private bool canResume; internal event Action? CommandInvoked; internal bool IsMenuOpen { get; private set; } internal MenuFlyout Menu => TrayMenu; internal MenuFlyoutPresenter? Presenter => Anchor.XamlRoot is { } root ? VisualTreeHelper.GetOpenPopupsForXamlRoot(root).Select(x => x.Child).OfType().FirstOrDefault() : null; internal TrayMenuWindow(FrameworkElement ownerRoot) { InitializeComponent(); this.ownerRoot = ownerRoot; var presenter = OverlappedPresenter.CreateForContextMenu(); presenter.SetBorderAndTitleBar(false, false); presenter.IsAlwaysOnTop = true; AppWindow.SetPresenter(presenter); AppWindow.IsShownInSwitchers = false; if (MicaController.IsSupported()) { TrayMenu.SystemBackdrop = new MicaBackdrop(); TrayMenu.MenuFlyoutPresenterStyle = (Style)Anchor.Resources["TrayMicaMenuPresenterStyle"]; } else TrayMenu.MenuFlyoutPresenterStyle = (Style)Anchor.Resources["TrayMenuPresenterStyle"]; ownerRoot.ActualThemeChanged += OwnerThemeChanged; Activated += Window_Activated; ApplyTheme(); } internal void ShowAt(PointInt32 screenPoint, bool canResume) { ObjectDisposedException.ThrowIf(disposed, this); requestedPoint = screenPoint; this.canResume = canResume; pending = true; if (active) { closing = true; TrayMenu.Hide(); } else BeginOpen(); } private void BeginOpen() { if (disposed || !pending || active) return; ApplyTheme(); ResumeItem.IsEnabled = canResume; var area = DisplayArea.GetFromPoint(requestedPoint, DisplayAreaFallback.Nearest).WorkArea; var x = Math.Clamp(requestedPoint.X, area.X, area.X + area.Width - 1); var y = Math.Clamp(requestedPoint.Y, area.Y, area.Y + area.Height - 1); // AppWindow coordinates are physical pixels. WinUI handles the popup's // monitor DPI and keeps the unconstrained menu inside the work area. AppWindow.MoveAndResize(new RectInt32(x, y, 1, 1)); AppWindow.Show(); Activate(); SetForegroundWindow(WinRT.Interop.WindowNative.GetWindowHandle(this)); DispatcherQueue.TryEnqueue(ShowPendingMenu); } private void Anchor_Loaded(object sender, RoutedEventArgs e) => ShowPendingMenu(); private void ShowPendingMenu() { if (disposed || !pending || active || Anchor.XamlRoot is null || !Anchor.IsLoaded) return; pending = false; active = true; TrayMenu.ShowAt(Anchor, new FlyoutShowOptions { Position = new(0, 0) }); } private void OwnerThemeChanged(FrameworkElement sender, object args) => ApplyTheme(); private void ApplyTheme() { Anchor.RequestedTheme = ownerRoot.ActualTheme; if (Presenter is { } presenter) presenter.RequestedTheme = ownerRoot.ActualTheme; } private void Menu_Opened(object sender, object e) { if (closing) { TrayMenu.Hide(); return; } IsMenuOpen = true; ApplyTheme(); } private void Menu_Closed(object sender, object e) { IsMenuOpen = false; active = closing = false; if (disposed) return; if (pending) BeginOpen(); else AppWindow.Hide(); } private void Window_Activated(object sender, WindowActivatedEventArgs args) { // A queued deactivation from the previous close can arrive after a // new menu has opened. Check the current foreground window first. var foreground = GetForegroundWindow(); var handle = WinRT.Interop.WindowNative.GetWindowHandle(this); if (args.WindowActivationState == WindowActivationState.Deactivated && IsMenuOpen && foreground != handle && GetAncestor(foreground, 3) != handle) Dismiss(); } private void Command_Click(object sender, RoutedEventArgs e) { if (sender is not MenuFlyoutItem { Tag: string tag } || !Enum.TryParse(tag, out var command)) return; Dismiss(); // Let the native flyout finish dispatching its click before opening or // closing windows and releasing the application's services. DispatcherQueue.TryEnqueue(() => { if (!disposed) CommandInvoked?.Invoke(command); }); } internal void Dismiss() { pending = false; IsMenuOpen = false; if (active) { closing = true; TrayMenu.Hide(); } AppWindow.Hide(); } public void Dispose() { if (disposed) return; Dismiss(); disposed = true; ownerRoot.ActualThemeChanged -= OwnerThemeChanged; Activated -= Window_Activated; Close(); } [DllImport("user32.dll")] private static extern bool SetForegroundWindow(nint window); [DllImport("user32.dll")] private static extern nint GetForegroundWindow(); [DllImport("user32.dll")] private static extern nint GetAncestor(nint window, uint flags); }