WPF win10窗体背景模糊

    internal enum AccentState
    {
        ACCENT_DISABLED = 0,
        ACCENT_ENABLE_GRADIENT = 1,
        ACCENT_ENABLE_TRANSPARENTGRADIENT = 2,
        ACCENT_ENABLE_BLURBEHIND = 3,
        ACCENT_INVALID_STATE = 4
    }

    [StructLayout(LayoutKind.Sequential)]
    internal struct AccentPolicy
    {
        public AccentState AccentState;
        public int AccentFlags;
        public int GradientColor;
        public int AnimationId;
    }

    [StructLayout(LayoutKind.Sequential)]
    internal struct WindowCompositionAttributeData
    {
        public WindowCompositionAttribute Attribute;
        public IntPtr Data;
        public int SizeOfData;
    }

    internal enum WindowCompositionAttribute
    {
        // ...
        WCA_ACCENT_POLICY = 19
        // ...
    }

    public partial class MainWindow : OWindow
    {
        [DllImport("user32.dll")]
        internal static extern int SetWindowCompositionAttribute(IntPtr hwnd, ref WindowCompositionAttributeData data);
        internal void EnableBlur()
        {
            var windowHelper = new WindowInteropHelper(this);

            var accent = new AccentPolicy();
            accent.AccentState = AccentState.ACCENT_ENABLE_BLURBEHIND;

            var accentStructSize = Marshal.SizeOf(accent);

            var accentPtr = Marshal.AllocHGlobal(accentStructSize);
            Marshal.StructureToPtr(accent, accentPtr, false);

            var data = new WindowCompositionAttributeData();
            data.Attribute = WindowCompositionAttribute.WCA_ACCENT_POLICY;
            data.SizeOfData = accentStructSize;
            data.Data = accentPtr;

            SetWindowCompositionAttribute(windowHelper.Handle, ref data);

            Marshal.FreeHGlobal(accentPtr);
        }
        public MainWindow()
        {
            InitializeComponent();
            Loaded += MainWindow_Loaded;
            CompositionTarget.Rendering += CompositionTarget_Rendering;
        }

        int fps = 0;
        Stopwatch stopwatch = new Stopwatch();
        private void CompositionTarget_Rendering(object? sender, EventArgs e)
        {
            if(!stopwatch.IsRunning) stopwatch.Start();
            fps++;
            if(stopwatch.Elapsed.TotalMilliseconds >= 1000)
            {
                tbFPS.Text = fps.ToString();
                fps = 0;
                stopwatch.Restart();
            }
        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            Background = new SolidColorBrush(Color.FromArgb(12, 0xFF, 0xFF, 0xFF));
            BorderBrush = Brushes.Gray;
            EnableBlur();
         }
    }

参考GitHub - Nukepayload2/sample-win10-aeroglass

posted @ 2023-11-11 10:02  HotSky  阅读(64)  评论(0编辑  收藏  举报