借助网络配置,控制Modbus工具的日志显示,避免卡死界面
智能大石头 authored at 2021-12-11 22:09:19
5.07 KiB
XCoder
using System;
using System.Collections.Specialized;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Styling;

namespace NewLife.XCoder.Services;

/// <summary>窗口外观:让系统标题栏跟随应用主题</summary>
/// <remarks>
/// Windows 的原生标题栏默认跟随系统设置,应用切到深色主题后仍会留下一条白色标题栏,
/// 在整片深色界面里非常扎眼。这里通过 DWM 的沉浸式深色模式属性把标题栏与边框一起染深,
/// 主题切换时实时更新。macOS/Linux 的原生标题栏本就跟随系统主题,无需额外处理。
/// </remarks>
public static class WindowChrome
{
    // Windows 10 20H1 及以后用 20,更早版本用 19
    private const Int32 DwmUseImmersiveDarkMode = 20;
    private const Int32 DwmUseImmersiveDarkModeOld = 19;

    private const Int32 SwHide = 0;
    private const Int32 SwShow = 5;

    // Windows 11(内部版本 22000)改属性即重画;Windows 10 只在窗口重新显示时才换色
    private static readonly Boolean _needFrameRefresh = Environment.OSVersion.Version.Build < 22000;

    private static readonly ConditionalWeakTable<Window, WindowState> _states = new();

    /// <summary>标题栏是否应使用深色</summary>
    /// <param name="variant">窗口实际生效的主题</param>
    /// <returns>深色主题返回 true</returns>
    public static Boolean IsDarkTitleBar(ThemeVariant? variant) => variant == ThemeVariant.Dark;

    /// <summary>接管桌面生命周期内的全部窗口,后续新建的窗口自动纳入</summary>
    /// <param name="lifetime">桌面生命周期</param>
    public static void Attach(IClassicDesktopStyleApplicationLifetime lifetime)
    {
        if (!OperatingSystem.IsWindows()) return;

        foreach (var window in lifetime.Windows) Attach(window);

        if (lifetime.Windows is INotifyCollectionChanged notify) notify.CollectionChanged += OnWindowsChanged;
    }

    /// <summary>让窗口标题栏跟随应用主题,并在主题切换时自动更新</summary>
    /// <param name="window">窗口</param>
    public static void Attach(Window window)
    {
        if (!OperatingSystem.IsWindows()) return;

        // 句柄要到窗口显示时才可用,因此首次应用放在 Opened;运行中切换主题需要重画一次边框
        window.Opened += (s, e) => Update(window);
        window.ActualThemeVariantChanged += (s, e) => Update(window, true);
        Update(window);
    }

    /// <summary>把窗口标题栏与边框染成深色或浅色</summary>
    /// <param name="handle">窗口句柄</param>
    /// <param name="dark">是否深色</param>
    /// <returns>系统是否接受;非 Windows 或句柄无效时返回 false</returns>
    public static Boolean ApplyTitleBar(IntPtr handle, Boolean dark)
    {
        if (!OperatingSystem.IsWindows() || handle == IntPtr.Zero) return false;

        var value = dark ? 1 : 0;
        return DwmSetWindowAttribute(handle, DwmUseImmersiveDarkMode, ref value, sizeof(Int32)) == 0 ||
               DwmSetWindowAttribute(handle, DwmUseImmersiveDarkModeOld, ref value, sizeof(Int32)) == 0;
    }

    private static void OnWindowsChanged(Object? sender, NotifyCollectionChangedEventArgs e)
    {
        if (e.NewItems == null) return;

        foreach (var item in e.NewItems)
        {
            if (item is Window window) Attach(window);
        }
    }

    private static void Update(Window window, Boolean refresh = false)
    {
        var handle = window.TryGetPlatformHandle()?.Handle;
        if (handle == null || handle.Value == IntPtr.Zero) return;

        var dark = IsDarkTitleBar(window.ActualThemeVariant);
        var state = _states.GetOrCreateValue(window);
        var changed = state.Applied != dark;

        if (ApplyTitleBar(handle.Value, dark)) state.Applied = dark;

        // 首次显示时属性在绘制前就已写入,无需重绘;只有运行中切换主题且确实换色时才补这一下
        if (refresh && changed && _needFrameRefresh && window.IsVisible) RefreshFrame(handle.Value);
    }

    private static void RefreshFrame(IntPtr handle)
    {
        // Windows 10 的 DWM 记着旧标题栏颜色,隐藏再显示才会按新属性重画
        var active = GetForegroundWindow() == handle;
        ShowWindow(handle, SwHide);
        ShowWindow(handle, SwShow);
        if (active) SetForegroundWindow(handle);
    }

    private sealed class WindowState
    {
        /// <summary>上次成功写入的标题栏配色;null 表示尚未写入</summary>
        public Boolean? Applied { get; set; }
    }

    [DllImport("dwmapi.dll", PreserveSig = true)]
    private static extern Int32 DwmSetWindowAttribute(IntPtr hwnd, Int32 attribute, ref Int32 value, Int32 size);

    [DllImport("user32.dll")]
    private static extern IntPtr GetForegroundWindow();

    [DllImport("user32.dll")]
    private static extern Boolean SetForegroundWindow(IntPtr hwnd);

    [DllImport("user32.dll")]
    private static extern Boolean ShowWindow(IntPtr hwnd, Int32 cmd);
}