最近在找其它资源时,无意间发现了一个程序可以将Area效果应用到整个窗体。感觉挺有意思,看了一下代码还是挺简单的。

首先需要两个API,DwmIsCompositionEnabled和DwmExtendFrameIntoClientArea。
DwmIsCompositionEnabled是用来判断系统是否开启了Area效果,当为False时为没有开启,这时有两种情况一个是系统不支持,另外一种是用户手动关闭了效果。如果是用户手动关闭的,你仍然可以使你的程序具有Area效果。否则是不可以的。
DwmExtendFrameIntoClientArea是用来使你的窗体具有Area效果,可以是整个窗体,也可以是窗体的一部分。这个函数的第一个参数是需要应用Area效果窗体的Handle,第二个参数是一个MARGINS结构可以指定在窗体的什么部位应用Area效果,如果是全部可以设置为-1,如果取消Area效果可以设置为0。
下面看一下这两个API的声明。
下面就是实现的代码了。
设置Area效果
OK,完成了。

首先需要两个API,DwmIsCompositionEnabled和DwmExtendFrameIntoClientArea。
DwmIsCompositionEnabled是用来判断系统是否开启了Area效果,当为False时为没有开启,这时有两种情况一个是系统不支持,另外一种是用户手动关闭了效果。如果是用户手动关闭的,你仍然可以使你的程序具有Area效果。否则是不可以的。
DwmExtendFrameIntoClientArea是用来使你的窗体具有Area效果,可以是整个窗体,也可以是窗体的一部分。这个函数的第一个参数是需要应用Area效果窗体的Handle,第二个参数是一个MARGINS结构可以指定在窗体的什么部位应用Area效果,如果是全部可以设置为-1,如果取消Area效果可以设置为0。
下面看一下这两个API的声明。
1
[DllImport("dwmapi.dll", PreserveSig = false)]
2
static extern void DwmExtendFrameIntoClientArea(IntPtr hwnd, ref MARGINS margins);
3
4
[DllImport("dwmapi.dll", PreserveSig = false)]
5
static extern bool DwmIsCompositionEnabled();

2

3

4

5

下面就是实现的代码了。
设置Area效果
1
public static bool Enable(Window window)
2
{
3
try
4
{
5
if (!DwmIsCompositionEnabled())
6
return false;
7
8
IntPtr hwnd = new WindowInteropHelper(window).Handle;
9
if (hwnd == IntPtr.Zero)
10
throw new InvalidOperationException("The Window must be shown before extending glass.");
11
12
// Set the background to transparent from both the WPF and Win32 perspectives
13
window.Background = System.Windows.Media.Brushes.Transparent;
14
HwndSource.FromHwnd(hwnd).CompositionTarget.BackgroundColor = Colors.Transparent;
15
16
MARGINS margins = new MARGINS(-1);
17
DwmExtendFrameIntoClientArea(hwnd, ref margins);
18
return true;
19
}
20
catch (Exception ex)
21
{
22
// could not change glass, but continue
23
System.Diagnostics.Debug.WriteLine(ex.Message);
24
return false;
25
}
26
}

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

取消Area效果
1
public static bool Disable(Window window)
2
{
3
try
4
{
5
if (!DwmIsCompositionEnabled())
6
return false;
7
8
IntPtr hwnd = new WindowInteropHelper(window).Handle;
9
if (hwnd == IntPtr.Zero)
10
throw new InvalidOperationException("The Window must be shown before extending glass.");
11
12
// Set the background to transparent from both the WPF and Win32 perspectives
13
window.Background = new SolidColorBrush(System.Windows.SystemColors.WindowColor);
14
HwndSource.FromHwnd(hwnd).CompositionTarget.BackgroundColor = System.Windows.SystemColors.WindowColor;
15
16
MARGINS margins = new MARGINS(0);
17
DwmExtendFrameIntoClientArea(hwnd, ref margins);
18
return true;
19
}
20
catch (Exception ex)
21
{
22
// could not change glass, but continue
23
System.Diagnostics.Debug.WriteLine(ex.Message);
24
return false;
25
}
26
}

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

OK,完成了。