广告
返回顶部
首页 > 资讯 > 后端开发 > 其他教程 >WPF实现窗体亚克力效果的示例代码
  • 751
分享到

WPF实现窗体亚克力效果的示例代码

2024-04-02 19:04:59 751人浏览 泡泡鱼
摘要

WPF 窗体设置亚克力效果 框架使用大于等于.net40。 Visual Studio 2022。 项目使用 MIT 开源许可协议。 WindowAcrylicB

WPF 窗体设置亚克力效果

框架使用大于等于.net40

Visual Studio 2022

项目使用 MIT 开源许可协议。

WindowAcrylicBlur 设置亚克力颜色。

Opacity 设置透明度。

实现代码

1) 准备WindowAcrylicBlur.cs如下:

using System;
using System.Runtime.InteropServices;
using System.windows;
using System.Windows.Interop;
using System.Windows.Media;
using Microsoft.Win32;
using Microsoft.Windows.shell;

namespace WPFDevelopers.Controls
{
    internal enum AccentState
    {
        ACCENT_DISABLED = 0,
        ACCENT_ENABLE_GRADIENT = 1,
        ACCENT_ENABLE_TRANSPARENTGRADIENT = 2,
        ACCENT_ENABLE_BLURBEHIND = 3,
        ACCENT_ENABLE_ACRYLICBLURBEHIND = 4,
        ACCENT_INVALID_STATE = 5
    }

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

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

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

    internal class WindowOldConfig
    {
        public bool AllowsTransparency;
        public Brush Background;
        public WindowChrome WindowChrome;
        public WindowStyle WindowStyle = WindowStyle.SingleBorderWindow;
    }


    internal class WindowOSHelper
    {
        public static Version GetWindowOSVersion()
        {
            var regKey = ReGIStry.LocalMachine.OpenSubKey(@"Software\Microsoft\Windows NT\CurrentVersion");

            int major;
            int minor;
            int build;
            int revision;
            try
            {
                var str = regKey.GetValue("CurrentMajorVersionNumber")?.ToString();
                int.TryParse(str, out major);

                str = regKey.GetValue("CurrentMinorVersionNumber")?.ToString();
                int.TryParse(str, out minor);

                str = regKey.GetValue("CurrentBuildNumber")?.ToString();
                int.TryParse(str, out build);

                str = regKey.GetValue("BaseBuildRevisionNumber")?.ToString();
                int.TryParse(str, out revision);

                return new Version(major, minor, build, revision);
            }
            catch (Exception)
            {
                return new Version(0, 0, 0, 0);
            }
            finally
            {
                regKey.Close();
            }
        }
    }


    public class WindowAcrylicBlur : Freezable
    {
        private static readonly Color _BackgtoundColor = Color.FromArgb(0x01, 0, 0, 0); //设置透明色 防止穿透

        [DllImport("user32.dll")]
        internal static extern int SetWindowCompositionAttribute(IntPtr hwnd, ref WindowCompositionAttributeData data);

        private static bool EnableAcrylicBlur(Window window, Color color, double opacity, bool enable)
        {
            if (window == null)
                return false;

            AccentState accentState;
            var vOsVersion = WindowOSHelper.GetWindowOSVersion();
            if (vOsVersion > new Version(10, 0, 17763)) //1809
                accentState = enable ? AccentState.ACCENT_ENABLE_ACRYLICBLURBEHIND : AccentState.ACCENT_DISABLED;
            else if (vOsVersion > new Version(10, 0))
                accentState = enable ? AccentState.ACCENT_ENABLE_BLURBEHIND : AccentState.ACCENT_DISABLED;
            else
                accentState = AccentState.ACCENT_DISABLED;

            if (opacity > 1)
                opacity = 1;

            var windowHelper = new WindowInteropHelper(window);

            var accent = new AccentPolicy();

            var opacityIn = (uint) (255 * opacity);

            accent.AccentState = accentState;

            if (enable)
            {
                var blurColor = (uint) ((color.R << 0) | (color.G << 8) | (color.B << 16) | (color.A << 24));
                var blurColorIn = blurColor;
                if (opacityIn > 0)
                    blurColorIn = (opacityIn << 24) | (blurColor & 0xFFFFFF);
                else if (opacityIn == 0 && color.A == 0)
                    blurColorIn = (0x01 << 24) | (blurColor & 0xFFFFFF);

                if (accent.GradientColor == blurColorIn)
                    return true;

                accent.GradientColor = blurColorIn;
            }

            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);

            return true;
        }

        private static void Window_Initialized(object sender, EventArgs e)
        {
            if (!(sender is Window window))
                return;

            var config = new WindowOldConfig
            {
                WindowStyle = window.WindowStyle,
                AllowsTransparency = window.AllowsTransparency,
                Background = window.Background
            };

            var vWindowChrome = WindowChrome.GetWindowChrome(window);
            if (vWindowChrome == null)
            {
                window.WindowStyle = WindowStyle.None; //一定要将窗口的背景色改为透明才行
                window.AllowsTransparency = true; //一定要将窗口的背景色改为透明才行
                window.Background = new SolidColorBrush(_BackgtoundColor); //一定要将窗口的背景色改为透明才行
            }
            else
            {
                config.WindowChrome = new WindowChrome
                {
                    GlassFrameThickness = vWindowChrome.GlassFrameThickness
                };
                window.Background = Brushes.Transparent; //一定要将窗口的背景色改为透明才行
                var vGlassFrameThickness = vWindowChrome.GlassFrameThickness;
                vWindowChrome.GlassFrameThickness = new Thickness(0, vGlassFrameThickness.Top, 0, 0);
            }

            SetWindowOldConfig(window, config);

            window.Initialized -= Window_Initialized;
        }

        private static void Window_Loaded(object sender, RoutedEventArgs e)
        {
            if (!(sender is Window window))
                return;

            var vBlur = GetWindowAcrylicBlur(window);
            if (vBlur != null)
                EnableAcrylicBlur(window, vBlur.BlurColor, vBlur.Opacity, true);

            window.Loaded -= Window_Loaded;
        }


        protected override Freezable CreateInstanceCore()
        {
            throw new NotImplementedException();
        }

        protected override void OnChanged()
        {
            base.OnChanged();
        }

        protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
        {
            base.OnPropertyChanged(e);
        }

        #region 开启Win11风格

        public static WindowAcrylicBlur GetWindowAcrylicBlur(DependencyObject obj)
        {
            return (WindowAcrylicBlur) obj.GetValue(WindowAcrylicBlurProperty);
        }

        public static void SetWindowAcrylicBlur(DependencyObject obj, WindowAcrylicBlur value)
        {
            obj.SetValue(WindowAcrylicBlurProperty, value);
        }

        public static readonly DependencyProperty WindowAcrylicBlurProperty =
            DependencyProperty.RegisterAttached("WindowAcrylicBlur", typeof(WindowAcrylicBlur),
                typeof(WindowAcrylicBlur),
                new PropertyMetadata(default(WindowAcrylicBlur), OnWindowAcryBlurPropertyChangedCallBack));

        private static void OnWindowAcryBlurPropertyChangedCallBack(DependencyObject d,
            DependencyPropertyChangedEventArgs e)
        {
            if (!(d is Window window))
                return;

            if (e.OldValue == null && e.NewValue == null)
                return;

            if (e.OldValue == null && e.NewValue != null)
            {
                window.Initialized += Window_Initialized;
                window.Loaded += Window_Loaded;
            }

            if (e.OldValue != null && e.NewValue == null)
            {
                var vConfig = GetWindowOldConfig(d);
                if (vConfig != null)
                {
                    window.WindowStyle = vConfig.WindowStyle;
                    window.AllowsTransparency = vConfig.AllowsTransparency;
                    window.Background = vConfig.Background;

                    if (vConfig.WindowChrome != null)
                    {
                        var vWindowChrome = WindowChrome.GetWindowChrome(window);
                        if (vWindowChrome != null)
                            vWindowChrome.GlassFrameThickness = vConfig.WindowChrome.GlassFrameThickness;
                    }
                }
            }

            if (e.OldValue == e.NewValue)
            {
                if (!window.IsLoaded)
                    return;

                var vBlur = e.NewValue as WindowAcrylicBlur;
                if (vBlur == null)
                    return;

                EnableAcrylicBlur(window, vBlur.BlurColor, vBlur.Opacity, true);
            }
        }

        #endregion


        #region 内部设置

        private static WindowOldConfig GetWindowOldConfig(DependencyObject obj)
        {
            return (WindowOldConfig) obj.GetValue(WindowOldConfigProperty);
        }

        private static void SetWindowOldConfig(DependencyObject obj, WindowOldConfig value)
        {
            obj.SetValue(WindowOldConfigProperty, value);
        }

        // Using a DependencyProperty as the backing store for WindowOldConfig.  This enables animation, styling, binding, etc...
        private static readonly DependencyProperty WindowOldConfigProperty =
            DependencyProperty.RegisterAttached("WindowOldConfig", typeof(WindowOldConfig), typeof(WindowAcrylicBlur),
                new PropertyMetadata(default(WindowOldConfig)));

        #endregion

        #region

        public Color BlurColor
        {
            get => (Color) GetValue(BlurColorProperty);
            set => SetValue(BlurColorProperty, value);
        }

        // Using a DependencyProperty as the backing store for BlurColor.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty BlurColorProperty =
            DependencyProperty.Register("BlurColor", typeof(Color), typeof(WindowAcrylicBlur),
                new PropertyMetadata(default(Color)));

        public double Opacity
        {
            get => (double) GetValue(OpacityProperty);
            set => SetValue(OpacityProperty, value);
        }

        // Using a DependencyProperty as the backing store for Opacity.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty OpacityProperty =
            DependencyProperty.Register("Opacity", typeof(double), typeof(WindowAcrylicBlur),
                new PropertyMetadata(default(double)));

        #endregion
    }
}

2) 使用AcrylicBlurWindowExample.xaml如下:

<Window x:Class="WPFDevelopers.Samples.ExampleViews.AcrylicBlurWindowExample"
        xmlns="Http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlfORMats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WPFDevelopers.Samples.ExampleViews"
        xmlns:wpfdev="https://GitHub.com/WPFDevelopersOrg/WPFDevelopers"
        mc:Ignorable="d" WindowStartupLocation="CenterScreen"
        ResizeMode="CanMinimize"
        Title="Login" Height="350" Width="400">
    <wpfdev:WindowChrome.WindowChrome>
        <wpfdev:WindowChrome  GlassFrameThickness="0 1 0 0"/>
    </wpfdev:WindowChrome.WindowChrome>
    <wpfdev:WindowAcrylicBlur.WindowAcrylicBlur>
        <wpfdev:WindowAcrylicBlur BlurColor="AliceBlue" Opacity="0.2"/>
    </wpfdev:WindowAcrylicBlur.WindowAcrylicBlur>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="40"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <StackPanel HorizontalAlignment="Right" 
                        Orientation="Horizontal"
                        Grid.Column="1"
                        wpfdev:WindowChrome.IsHitTestVisibleInChrome="True">
            <Button Style="{DynamicResource WindowButtonStyle}"
                    Command="{Binding CloseCommand,RelativeSource={RelativeSource AncestorType=local:AcrylicBlurWindowExample}}" Cursor="Hand">
                <Path Width="10" Height="10"
                      HorizontalAlignment="Center"
                      VerticalAlignment="Center"
                      Data="{DynamicResource PathMetroWindowClose}"
                      Fill="Red"
                      Stretch="Fill" />
            </Button>
        </StackPanel>
        <StackPanel Grid.Row="1" Margin="40,0,40,0"
                    wpfdev:WindowChrome.IsHitTestVisibleInChrome="True">
            <Image Source="/WPFDevelopers.ico" Width="80" Height="80"/>
            <TextBox wpfdev:ElementHelper.IsWatermark="True" wpfdev:ElementHelper.Watermark="账户" Margin="0,20,0,0" Cursor="Hand"/>
            <PassWordBox wpfdev:ElementHelper.IsWatermark="True" wpfdev:ElementHelper.Watermark="密码"  Margin="0,20,0,0" Cursor="Hand"/>
            <Button x:Name="LoginButton" 
                    Content="登 录" 
                    Margin="0,20,0,0"
                    Style="{StaticResource PrimaryButton}"/>
            <Grid Margin="0 20 0 0">
                <TextBlock FontSize="12">
                    <Hyperlink Foreground="Black" TextDecorations="None">忘记密码</Hyperlink>
                </TextBlock>
                <TextBlock FontSize="12" HorizontalAlignment="Right" Margin="0 0 -1 0">
                    <Hyperlink Foreground="#4370F5" TextDecorations="None">注册账号</Hyperlink>
                </TextBlock>
            </Grid>
        </StackPanel>

    </Grid>
</Window>

3) 使用AcrylicBlurWindowExample.xaml.cs如下:

using System.Windows;
using System.Windows.Input;
using WPFDevelopers.Samples.Helpers;

namespace WPFDevelopers.Samples.ExampleViews
{
    /// <summary>
    /// AcrylicBlurWindowExample.xaml 的交互逻辑
    /// </summary>
    public partial class AcrylicBlurWindowExample : Window
    {
        public AcrylicBlurWindowExample()
        {
            InitializeComponent();
        }
        public ICommand CloseCommand => new RelayCommand(obj =>
        {
           Close();
        });
    }
}

实现效果

到此这篇关于WPF实现窗体亚克力效果的示例代码的文章就介绍到这了,更多相关WPF窗体亚克力内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: WPF实现窗体亚克力效果的示例代码

本文链接: https://www.lsjlt.com/news/168841.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • WPF实现窗体亚克力效果的示例代码
    WPF 窗体设置亚克力效果 框架使用大于等于.NET40。 Visual Studio 2022。 项目使用 MIT 开源许可协议。 WindowAcrylicB...
    99+
    2022-11-13
  • WPF实现抽屉菜单效果的示例代码
    WPF 实现抽屉菜单 框架使用大于等于.NET40;Visual Studio 2022;项目使用 MIT 开源许可协议;更多效果可以通过GitHub[1]|码云...
    99+
    2022-11-13
    WPF 抽屉菜单 WPF 菜单
  • 基于WPF实现弹幕效果的示例代码
    WPF 实现弹幕效果 框架使用大于等于.NET40; Visual Studio 2022; 项目使用 MIT 开源许可协议; 此篇代码目的只是为了分享思路 实现...
    99+
    2022-11-13
  • 基于WPF实现面包屑效果的示例代码
    WPF 简单实现面包屑 框架使用.NET4 至 .NET6; Visual Studio 2022; 面包屑展示使用控件如下: Button 做首页按钮,当点击时回到首页。...
    99+
    2023-05-17
    WPF实现面包屑效果 WPF面包屑效果 WPF面包屑
  • WPF实现文本描边+外发光效果的示例代码
    解决思路: (1)描边效果可以将文本字符串用GDI+生成Bitmap,然后转成BitmapImage,再用WPF的Image控件显示。 (2)外发光效果用WPF自带的Effect实现...
    99+
    2022-11-13
  • 基于WPF实现3D画廊动画效果的示例代码
    接下来想做一个图廊,所以并没有必要用立方体,只需做一些“墙壁”就行了。 而在一个平面上建起另一个矩形的平面,实则非常容易,只需输入墙角的两点和高度就可以了,这...
    99+
    2023-02-28
    WPF实现3D画廊效果 WPF 3D画廊 WPF 3D
  • C++实现将图片转换为马赛克效果的示例代码
    这个程序将图片转换为马赛克效果。 算法原理:求出每个小方块内所有像素的颜色平均值,然后用来设置为该小方块的颜色。依次处理每个小方块,即可实现马赛克效果。 完整代码如下 // 程序名称...
    99+
    2023-01-14
    C++图片转马赛克 C++ 图片 马赛克
  • Python实现屏幕代码雨效果的示例代码
    直接上代码 import pygame import random def main(): # 初始化pygame pygame.init() #...
    99+
    2022-11-13
  • AndroidFlutter实现点赞效果的示例代码
    目录前言绘制小手完整源码前言 点赞这个动作不得不说在社交、短视频等App中实在是太常见了,当用户手指按下去的那一刻,给用户一个好的反馈效果也是非常重要的,这样用户点起赞来才会有一种强...
    99+
    2022-11-13
  • JavaScript实现流星雨效果的示例代码
    目录演示技术栈源码首先建立星星对象让星星闪亮起来创建流星雨对象让流星动起来演示 上一次做了一个雨滴的动画,顺着这种思维正好可以改成流星雨,嘿嘿我真是一个小机灵。 技术栈 还是先建立...
    99+
    2022-11-13
  • Unity实现跑马灯效果的示例代码
    目录一、效果二、需要动画插件DOTween三、脚本1.每个格子上的脚本文件2.管理脚本文件一、效果 二、需要动画插件DOTween 下载地址 三、脚本 1.每个格子上的脚本文件 u...
    99+
    2022-11-13
  • C#实现跑马灯效果的示例代码
    目录文章描述开发环境开发工具实现代码实现效果文章描述 跑马灯效果,功能效果大家应该都知道,就是当我们的文字过长,整个页面放不下的时候(一般用于公告等),可以让它自动实现来回滚动,以让...
    99+
    2022-11-13
    C#实现跑马灯效果 C# 跑马灯
  • 基于Python实现烟花效果的示例代码
    python烟花代码 如下 # -*- coding: utf-8 -*- import math, random,time import threading import tki...
    99+
    2022-11-13
  • Python实现图像去雾效果的示例代码
    目录修改部分训练测试数据集下载地址修改部分 我利用该代码进行了去雾任务,并对原始代码进行了增删,去掉了人脸提取并对提取人脸美化的部分,如下图 增改了一些数据处理代码,Create_...
    99+
    2022-11-13
  • android实现音乐跳动效果的示例代码
    效果图 实现 整体的流程图如下 上面主要步骤分为3个 1、计算宽度能放下多少列的音频块。 2、计算每一列中音频块的个数 3、绘制音频块 1、计算宽度能放下多少列的音频块。 ...
    99+
    2022-11-12
  • Qt实现字幕滚动效果的示例代码
    目录一、项目介绍二、项目基本配置三、UI界面设计四、主程序实现4.1 widget.h头文件4.2 widget.cpp源文件五、效果演示一、项目介绍 利用QTimer实现字幕滚动功...
    99+
    2022-11-13
  • JavaScript实现扯网动画效果的示例代码
    目录演示技术栈源码css控制js部分演示 技术栈 JavaScript prototype(原型对象): 所有的 JavaScript 对象都会从一个 prototype(原型对象...
    99+
    2022-11-13
  • python实现字母闪烁效果的示例代码
    目录1. 介绍2. 完整代码效果图 1. 介绍 屏幕上随机闪烁的代码块,一定能满足我们对于电影中黑客的一丝丝设想,这次,让我们用简简单单的30行python代码,实现这个效果。 前...
    99+
    2022-11-11
  • vue实现无缝轮播效果的示例代码
    小编给大家分享一下vue实现无缝轮播效果的示例代码,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!具体内容如下首先创建两个vue组件Sweiper.vue和Swei...
    99+
    2023-06-15
  • Flutter实现牛顿摆动画效果的示例代码
    目录前言实现步骤1、绘制静态效果2、加入动画两个关键点完整源码总结前言 牛顿摆大家应该都不陌生,也叫碰碰球、永动球(理论情况下),那么今天我们用Flutter实现这么一个理论中的永动...
    99+
    2022-11-13
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作