我正在尝试创建一个WPF应用程序,其中包含一个半透明无边框窗口,可以模糊其后面的背景。
以下是我想要实现的示例:
我尝试使用 DwmEnableBlurBehindWindow,但它只适用于Windows Vista/7。
我正在寻找在Windows 7、8和10上都能使用的解决方案。
我正在尝试创建一个WPF应用程序,其中包含一个半透明无边框窗口,可以模糊其后面的背景。
以下是我想要实现的示例:
我尝试使用 DwmEnableBlurBehindWindow,但它只适用于Windows Vista/7。
我正在寻找在Windows 7、8和10上都能使用的解决方案。
对于任何感兴趣的人,我已经找到了一个Windows 10的解决方案。然而,在Windows 8上似乎不可能实现;正如David Heffernan所提到的,DwmEnableBlurBehindWindow
已从Windows 8中删除。然而,Microsoft在Windows 10中重新引入了一种解决方案来实现这种效果。
DwmEnableBlurBehindWindow
Windows 8
尽管Windows 8已经是一个被彻底忘却的死胡同,但我们仍然需要确保我们的程序在不同版本的系统中表现一致。如果没有动态背景特效,并且窗口相对较小(比如消息框或类似于我们自己应用程序窗口的),则可以在Loaded
事件处理程序中采用手动模糊窗口后面的屏幕图像的解决方案。
var screen = window.Owner.PointToScreen(new System.Windows.Point((window.Owner.ActualWidth - window.ActualWidth) / 2, (window.Owner.ActualHeight - window.ActualHeight) / 2));
var rect = new Rectangle((int)screen.X, (int)screen.Y, (int)window.ActualWidth, (int)window.ActualHeight);
var bitmap = new Bitmap(rect.Width, rect.Height);
using (var graphics = Graphics.FromImage(bitmap))
graphics.CopyFromScreen(rect.Left, rect.Top, 0, 0, rect.Size);
border.Background = new ImageBrush(ApplyGaussianBlur(bitmap.ToBitmapImage())) {
TileMode = TileMode.None,
Stretch = Stretch.None,
AlignmentX = AlignmentX.Center,
AlignmentY = AlignmentY.Center,
};
其中border
是最外层的Border
,通常完全为空,仅在Windows 8上使用。
辅助函数是通常的位图转换:
public static BitmapSource ToBitmapImage(this System.Drawing.Bitmap image) {
var hBitmap = image.GetHbitmap();
var bitmap = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
DeleteObject(hBitmap);
return bitmap;
}
ApplyGaussianBlur()
最好使用像 WriteableBitmapEx
这样的直接位图操作包来解决,需要进行必要的修改。
自Windows 8开始,Microsoft移除了玻璃效果。这就解释了为什么你期望的模糊效果在Windows 8及以后的版本中没有观察到。你将不得不学会在这些操作系统上没有它而生活。