windows 10 透明毛玻璃,winform和wpf方法 - 羽铉

时间:2024-02-19 19:21:28
win10的透明毛玻璃,winform和wpf方法,win7、8不能用,只是win10
 public partial class Form1 : Form
    {
        [DllImport("user32.dll")]
        internal static extern int SetWindowCompositionAttribute(IntPtr hwnd, ref WindowCompositionAttributeData data);

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

        internal enum WindowCompositionAttribute
        {
            WCA_ACCENT_POLICY = 19
        }

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

        internal void EnableBlur()
        {
            var accent = new AccentPolicy();
            var accentStructSize = Marshal.SizeOf(accent);
            accent.AccentState = AccentState.ACCENT_ENABLE_BLURBEHIND;

            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(this.Handle, ref data);

            Marshal.FreeHGlobal(accentPtr);
        }
...................
...................
private void Form1_Load(object sender, EventArgs e)
        {
            EnableBlur();
        }

窗体背景设置比如Red,然后TransparencyKey=Red,就有行了。

如果使用WPF,修改:
internal void EnableBlur()
{
    var windowHelper = new WindowInteropHelper(this);
    ......
    ......
    SetWindowCompositionAttribute(windowHelper.Handle, ref data);
    ......
}

 

posted on 2018-01-31 22:13  羽铉  阅读(3172)  评论(0编辑  收藏  举报