Skip to content

Instantly share code, notes, and snippets.

@odalet
Created February 7, 2021 15:53
Show Gist options
  • Save odalet/2aa34bedc8070ace1919c70cd0581a6d to your computer and use it in GitHub Desktop.
Save odalet/2aa34bedc8070ace1919c70cd0581a6d to your computer and use it in GitHub Desktop.
using System;
using System.Runtime.InteropServices;
// https://stackoverflow.com/questions/66002667/pinvoking-user32-dll-setwindowcompositionattribute-via-powershell
public static class NativeMethods
{
[DllImport("user32.dll")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
// See http://pinvoke.net/default.aspx/Enums/DwmSetWindowAttribute.html
public enum DWMWINDOWATTRIBUTE : uint
{
NCRenderingEnabled = 1,
NCRenderingPolicy,
TransitionsForceDisabled,
AllowNCPaint,
CaptionButtonBounds,
NonClientRtlLayout,
ForceIconicRepresentation,
Flip3DPolicy,
ExtendedFrameBounds,
HasIconicBitmap,
DisallowPeek,
ExcludedFromPeek,
Cloak,
Cloaked,
FreezeRepresentation
}
[DllImport("dwmapi.dll", PreserveSig = true)]
public static extern int DwmSetWindowAttribute(IntPtr hwnd, DWMWINDOWATTRIBUTE attr, ref int attrValue, int attrSize);
// Grabbed from https://gist.github.com/riverar/fd6525579d6bbafc6e48
[DllImport("user32.dll")]
private static extern int SetWindowCompositionAttribute(IntPtr hwnd, ref WindowCompositionAttributeData data);
[StructLayout(LayoutKind.Sequential)]
private struct WindowCompositionAttributeData
{
public WindowCompositionAttribute Attribute;
public IntPtr Data;
public int SizeOfData;
}
private enum WindowCompositionAttribute
{
// ...
WCA_ACCENT_POLICY = 19
// ...
}
private enum AccentState
{
ACCENT_DISABLED = 0,
ACCENT_ENABLE_GRADIENT = 1,
ACCENT_ENABLE_TRANSPARENTGRADIENT = 2,
ACCENT_ENABLE_BLURBEHIND = 3,
ACCENT_INVALID_STATE = 4
}
[StructLayout(LayoutKind.Sequential)]
private struct AccentPolicy
{
public AccentState AccentState;
public int AccentFlags;
public int GradientColor;
public int AnimationId;
}
// And here, expose some methods that will simplify the use of SetWindowCompositionAttribute from the outside
// Adapted from https://www.kechuang.org/t/79675
public static void EnableBlur(IntPtr HWnd, bool hasFrame = true)
{
var accent = new AccentPolicy
{
AccentState = AccentState.ACCENT_ENABLE_BLURBEHIND
};
if (hasFrame)
accent.AccentFlags = 0x20 | 0x40 | 0x80 | 0x100;
var accentStructSize = Marshal.SizeOf(accent);
var accentPtr = Marshal.AllocHGlobal(accentStructSize);
Marshal.StructureToPtr(accent, accentPtr, false);
var data = new WindowCompositionAttributeData
{
Attribute = WindowCompositionAttribute.WCA_ACCENT_POLICY,
SizeOfData = accentStructSize,
Data = accentPtr
};
_ = SetWindowCompositionAttribute(HWnd, ref data);
Marshal.FreeHGlobal(accentPtr);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment