经过测试只能在Windows7 下正常使用,在Win8或者Xp下面无法正常显示毛玻璃效果。
首先你要先创建一个结构体如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
[StructLayout(LayoutKind.Sequential)]
public struct MARGINS
{
public MARGINS(Thickness t)
{
Left = (int)t.Left;
Right = (int)t.Right;
Top = (int)t.Top;
Bottom = (int)t.Bottom;
}
public int Left;
public int Right;
public int Top;
public int Bottom;
}
|
之后再创建一个辅助类:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
public class GlassHelper
{
[DllImport("dwmapi.dll", PreserveSig = false)]
static extern void DwmExtendFrameIntoClientArea(
IntPtr hWnd, ref MARGINS pMarInset);
[DllImport("dwmapi.dll", PreserveSig = false)]
static extern bool DwmIsCompositionEnabled();
public static bool ExtendGlassFrame(Window window, Thickness margin)
{
if (!DwmIsCompositionEnabled())
return false;
IntPtr hwnd = new WindowInteropHelper(window).Handle;
if (hwnd == IntPtr.Zero)
throw new InvalidOperationException(
"The Window must be shown before extending glass.");
// 将Win32或者WPF程序背景设置为透明
window.Background = Brushes.Transparent;
HwndSource.FromHwnd(hwnd).CompositionTarget.BackgroundColor = Colors.Transparent;
MARGINS margins = new MARGINS(margin);
DwmExtendFrameIntoClientArea(hwnd, ref margins);
return true;
}
}
|
然后你只需要重写 OnSourceInitialized
方法即可。
1
2
3
4
5
|
protected override void OnSourceInitialized(EventArgs e)
{
base.OnSourceInitialized(e);
GlassHelper.ExtendGlassFrame(this, new Thickness(-1));
}
|
效果图: