自Windows Vista起,Windows的桌面效果就增加了对Aero透明玻璃效果的支持,系统默认的话只是对标题栏或者菜单栏进行半透明处理,如果想实现整个窗口都Aero化的话,得引用一个系统DLL来实现。首先看效果图:
这个效果是通过DWM(Destop Window Manager)中的一个API来实现的,关键的代码如下:
1
private
void
ExtendAeroGlass(Window window)
2
{
3
try
4
{
5
//
为WPF程序获取窗口句柄
6
IntPtr mainWindowPtr
=
new
WindowInteropHelper(window).Handle;
7
HwndSource mainWindowSrc
=
HwndSource.FromHwnd(mainWindowPtr);
8
mainWindowSrc.CompositionTarget.BackgroundColor
=
Colors.Transparent;
9
10
//
设置Margins
11
MARGINS margins
=
new
MARGINS();
12
13
//
扩展Aero Glass
14
margins.cxLeftWidth
=
-
1
;
15
margins.cxRightWidth
=
-
1
;
16
margins.cyTopHeight
=
-
1
;
17
margins.cyBottomHeight
=
-
1
;
18
19
int
hr
=
DwmExtendFrameIntoClientArea(mainWindowSrc.Handle,
ref
margins);
20
if
(hr
<
0
)
21
{
22
MessageBox.Show(
"
DwmExtendFrameIntoClientArea Failed
"
);
23
}
24
}
25
catch
(DllNotFoundException)
26
{
27
Application.Current.MainWindow.Background
=
Brushes.White;
28
}
29
}
30
31
[StructLayout(LayoutKind.Sequential)]
32
public
struct
MARGINS
33
{
34
public
int
cxLeftWidth;
35
public
int
cxRightWidth;
36
public
int
cyTopHeight;
37
public
int
cyBottomHeight;
38
};
39
40
[DllImport(
"
DwmApi.dll
"
)]
41
public
static
extern
int
DwmExtendFrameIntoClientArea(
42
IntPtr hwnd,
43
ref
MARGINS pMarInset);
从代码中得知,我们需要引用一个DwmApi.dll文件,然后定义一个函数去实现拓展Aero区域,从而实现整个窗口的Aero化。