WPF 几行代码实现窗体毛玻璃效果(Aero Glass)

创建一个叫AeroGlass.cs 的类,代码如下:

 1 using System;
 2 using System.Runtime.InteropServices;
 3 using System.Windows;
 4 using System.Windows.Interop;
 5 using System.Windows.Media;
 6 
 7 [StructLayout(LayoutKind.Sequential)]
 8 public struct MARGINS
 9 {
10     public MARGINS(Thickness t)
11     {
12         Left = (int)t.Left;
13         Right = (int)t.Right;
14         Top = (int)t.Top;
15         Bottom = (int)t.Bottom;
16     }
17     public int Left;
18     public int Right;
19     public int Top;
20     public int Bottom;
21 }
22 
23 public class GlassHelper
24 {
25     [DllImport("dwmapi.dll", PreserveSig = false)]
26     static extern void DwmExtendFrameIntoClientArea(
27         IntPtr hWnd, ref MARGINS pMarInset);
28     [DllImport("dwmapi.dll", PreserveSig = false)]
29         static extern bool DwmIsCompositionEnabled();
30 
31     public static bool ExtendGlassFrame(Window window, Thickness margin)
32     {
33         if (!DwmIsCompositionEnabled())
34             return false;
35 
36         IntPtr hwnd = new WindowInteropHelper(window).Handle;
37         if (hwnd == IntPtr.Zero)
38             throw new InvalidOperationException(
39             "The Window must be shown before extending glass.");
40 
41         // Set the background to transparent from both the WPF and Win32 perspectives
42         window.Background = Brushes.Transparent;
43         HwndSource.FromHwnd(hwnd).CompositionTarget.BackgroundColor = Colors.Transparent;
44 
45         MARGINS margins = new MARGINS(margin);
46         DwmExtendFrameIntoClientArea(hwnd, ref margins);
47         return true;
48     }
49 }

把这段代码加到主窗体就可以了!

1 protected override void OnSourceInitialized(EventArgs e)
2         {
3             base.OnSourceInitialized(e);
4             GlassHelper.ExtendGlassFrame(this, new Thickness(-1));
5         }

 

posted @ 2012-08-23 17:11  Lyghost  阅读(2251)  评论(0编辑  收藏  举报