WPF中打造半透明窗口效果 - [WPF开发]
自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);
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化。
参考资料:
1、关于WPF窗口的知识:http://www.cnblogs.com/libenqing/archive/2011/04/07/2007817.html
2、原文出处:http://www.cnblogs.com/gnielee/archive/2010/10/04/windows7-extend-aero-glass.html
@:卿之 → http://www.cnblogs.com/wpdev
©:博文是本人当时的学习笔记及知识整理,由于自身局限错误在所难免,敬请斧正.
©:本文版权属于博客园和本人,版权基于署名 2.5 中国大陆许可协议发布,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接和署名卿之(包含链接),不得删节,否则保留追究法律责任的权利。