XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEWorkflow

【WinUI】XFE基于windows的工作流

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Runtime.InteropServices;
using Microsoft.UI.Windowing;
using XFEWorkflow.Controls;
using Windows.Graphics;

namespace XFEWorkflow.Services;

public sealed class TrayService : IDisposable
{
    private const uint TrayMessage = 0x8000 + 42;
    private const int HotKeyId = 0x5846;
    private readonly nint window;
    private readonly MainWindow owner;
    private readonly SubclassProc procedure;
    private NotifyIconData icon;
    private TrayMenuWindow? menu;
    private bool quitting, disposed;
    public TrayService(MainWindow owner)
    {
        this.owner = owner; window = WinRT.Interop.WindowNative.GetWindowHandle(owner); procedure = WindowProc;
        if (!SetWindowSubclass(window, procedure, 1, 0)) throw new System.ComponentModel.Win32Exception();
        icon = new() { Size = (uint)Marshal.SizeOf<NotifyIconData>(), Window = window, Id = 1, Flags = 1 | 2 | 4,
            CallbackMessage = TrayMessage, Tip = "XFEWorkflow · 双击打开 · Ctrl+Alt+F12 紧急停止",
            Icon = LoadImage(0, Path.Combine(AppContext.BaseDirectory, "Assets", "appicon.ico"), 1, 32, 32, 0x10) };
        ShellNotifyIcon(0, ref icon);
        RegisterHotKey(window, HotKeyId, 1 | 2 | 0x4000, 0x7B);
        owner.AppWindow.Closing += Closing;
    }
    private void Closing(AppWindow sender, AppWindowClosingEventArgs args)
    { if (!quitting) { args.Cancel = true; sender.Hide(); } }
    private nint WindowProc(nint hwnd, uint message, nuint wParam, nint lParam, nuint subclassId, nuint data)
    {
        if (message == 0x0312 && (int)wParam == HotKeyId) { EmergencyStop(); return 0; }
        if (message == TrayMessage)
        {
            if ((uint)lParam is 0x0203 or 0x0202) Show();
            else if ((uint)lParam is 0x0205 or 0x007B)
            {
                GetCursorPos(out var point);
                owner.DispatcherQueue.TryEnqueue(() => ShowContextMenu(new(point.X, point.Y)));
            }
            return 0;
        }
        return DefSubclassProc(hwnd, message, wParam, lParam);
    }
    internal TrayMenuWindow? ContextMenu => menu;
    internal void ShowContextMenu(PointInt32 point)
    {
        if (disposed || quitting) return;
        if (menu is null)
        {
            menu = new((FrameworkElement)owner.Content);
            menu.CommandInvoked += InvokeCommand;
        }
        menu.ShowAt(point, AppServices.Current.Scheduler.IsSuspended);
    }
    private void InvokeCommand(TrayCommand command)
    {
        if (disposed || quitting) return;
        switch (command)
        {
            case TrayCommand.Open: Show(); break;
            case TrayCommand.EmergencyStop: EmergencyStop(); break;
            case TrayCommand.Resume: _ = ResumeAsync(); break;
            case TrayCommand.Exit: _ = ExitAsync(); break;
        }
    }
    private async Task ResumeAsync()
    {
        try { await AppServices.Current.Scheduler.ResumeAsync(); }
        catch (OperationCanceledException) when (quitting) { }
        catch (Exception ex) { Console.WriteLine("[ERROR]恢复自动调度:" + ex.Message); }
    }
    public void Show() { menu?.Dismiss(); owner.AppWindow.Show(); owner.Activate(); SetForegroundWindow(window); }
    public void EmergencyStop()
    {
        AppServices.Current.Scheduler.Suspend();
        AppServices.Current.Desktop.EmergencyStop();
        AppServices.Current.ScreenTools.CancelSelection();
        _ = AppServices.Current.Runs.StopAllAsync();
    }
    public async Task ExitAsync()
    {
        if (quitting) return; quitting = true;
        try { await AppServices.Current.DisposeAsync(); }
        catch (Exception ex) { Console.WriteLine("[ERROR]退出清理:" + ex.Message); }
        finally { Dispose(); owner.Close(); }
    }
    public void Dispose()
    {
        if (disposed) return; disposed = true;
        if (menu is not null) { menu.CommandInvoked -= InvokeCommand; menu.Dispose(); menu = null; }
        owner.AppWindow.Closing -= Closing; UnregisterHotKey(window, HotKeyId);
        ShellNotifyIcon(2, ref icon); if (icon.Icon != 0) DestroyIcon(icon.Icon);
        RemoveWindowSubclass(window, procedure, 1);
    }
    private delegate nint SubclassProc(nint hwnd, uint message, nuint wParam, nint lParam, nuint subclassId, nuint data);
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] private struct NotifyIconData
    {
        public uint Size; public nint Window; public uint Id, Flags, CallbackMessage; public nint Icon;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] public string Tip;
        public uint State, StateMask;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public string Info;
        public uint Timeout;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)] public string InfoTitle;
        public uint InfoFlags; public Guid Guid; public nint BalloonIcon;
    }
    [StructLayout(LayoutKind.Sequential)] private struct Point { public int X, Y; }
    [DllImport("comctl32.dll")] private static extern bool SetWindowSubclass(nint hwnd, SubclassProc proc, nuint id, nuint data);
    [DllImport("comctl32.dll")] private static extern bool RemoveWindowSubclass(nint hwnd, SubclassProc proc, nuint id);
    [DllImport("comctl32.dll")] private static extern nint DefSubclassProc(nint hwnd, uint msg, nuint w, nint l);
    [DllImport("shell32.dll", EntryPoint = "Shell_NotifyIconW", CharSet = CharSet.Unicode)] private static extern bool ShellNotifyIcon(uint message, ref NotifyIconData data);
    [DllImport("user32.dll", CharSet = CharSet.Unicode, EntryPoint = "LoadImageW")] private static extern nint LoadImage(nint instance, string name, uint type, int width, int height, uint flags);
    [DllImport("user32.dll")] private static extern bool RegisterHotKey(nint hwnd, int id, uint modifiers, uint key);
    [DllImport("user32.dll")] private static extern bool UnregisterHotKey(nint hwnd, int id);
    [DllImport("user32.dll")] private static extern bool SetForegroundWindow(nint hwnd);
    [DllImport("user32.dll")] private static extern bool GetCursorPos(out Point point);
    [DllImport("user32.dll")] private static extern bool DestroyIcon(nint icon);
}