这是一个快速组合而成的 WPF 解决方案。它使用hRgnBlur
of the DWM_BLURBEHIND http://msdn.microsoft.com/en-us/library/windows/desktop/aa969500.aspx结构和一些互操作。
此示例将在窗口上应用椭圆形背景模糊。
您可以轻松地将其转换为附加属性或行为以实现 MVVM 友好。多听听也是一个好主意WM_DWMCOMPOSITIONCHANGED
消息并根据需要重新应用模糊。
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
WindowStyle = WindowStyle.None;
AllowsTransparency = true;
SourceInitialized += OnSourceInitialized;
}
private void OnSourceInitialized(object sender, EventArgs eventArgs)
{
if (!NativeMethods.DwmIsCompositionEnabled())
return;
var hwnd = new WindowInteropHelper(this).Handle;
var hwndSource = HwndSource.FromHwnd(hwnd);
var sizeFactor = hwndSource.CompositionTarget.TransformToDevice.Transform(new Vector(1.0, 1.0));
Background = System.Windows.Media.Brushes.Transparent;
hwndSource.CompositionTarget.BackgroundColor = Colors.Transparent;
using (var path = new GraphicsPath())
{
path.AddEllipse(0, 0, (int)(ActualWidth * sizeFactor.X), (int)(ActualHeight * sizeFactor.Y));
using (var region = new Region(path))
using (var graphics = Graphics.FromHwnd(hwnd))
{
var hRgn = region.GetHrgn(graphics);
var blur = new NativeMethods.DWM_BLURBEHIND
{
dwFlags = NativeMethods.DWM_BB.DWM_BB_ENABLE | NativeMethods.DWM_BB.DWM_BB_BLURREGION | NativeMethods.DWM_BB.DWM_BB_TRANSITIONONMAXIMIZED,
fEnable = true,
hRgnBlur = hRgn,
fTransitionOnMaximized = true
};
NativeMethods.DwmEnableBlurBehindWindow(hwnd, ref blur);
region.ReleaseHrgn(hRgn);
}
}
}
[SuppressUnmanagedCodeSecurity]
private static class NativeMethods
{
[StructLayout(LayoutKind.Sequential)]
public struct DWM_BLURBEHIND
{
public DWM_BB dwFlags;
public bool fEnable;
public IntPtr hRgnBlur;
public bool fTransitionOnMaximized;
}
[Flags]
public enum DWM_BB
{
DWM_BB_ENABLE = 1,
DWM_BB_BLURREGION = 2,
DWM_BB_TRANSITIONONMAXIMIZED = 4
}
[DllImport("dwmapi.dll", PreserveSig = false)]
public static extern bool DwmIsCompositionEnabled();
[DllImport("dwmapi.dll", PreserveSig = false)]
public static extern void DwmEnableBlurBehindWindow(IntPtr hwnd, ref DWM_BLURBEHIND blurBehind);
}
}
与以下 XAML 一起使用:
<Window x:Class="WpfTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="200" Width="300" WindowStartupLocation="CenterScreen">
<Border Background="#800000FF" Margin="30">
<TextBlock Text="Hello, world!" VerticalAlignment="Center" HorizontalAlignment="Center" />
</Border>
</Window>
结果是: