技术开发 频道

详解WPF扩展玻璃效果(Aero Glass)

    【IT168 技术文档】Windows 7 操作系统默认具有一款玻璃效果主题(Aero Glass)。如果选择了该款主题,所有的应用程序标题栏都会处于玻璃透明效果(如下图)。这个功能是由Desktop Window Manager(DWM)服务支持的。

1
 

  默认情况下,我们编写的应用程序在Windows 7 中也只有标题栏和窗口框架会具备玻璃效果,其他区域仍是不透明状态(如下图)。如果想将程序整体都改为上图IE 窗口的效果,可以使用DWM API 将玻璃区域进行扩展。

1
 

  首先,从dwmapi.dll 中调取DwmExtendFrameIntoClientArea 方法。

[StructLayout(LayoutKind.Sequential)]
public struct MARGINS
{
    
public int cxLeftWidth;      
    
public int cxRightWidth;    
    
public int cyTopHeight;      
    
public int cyBottomHeight;  
};

[DllImport(
"DwmApi.dll")]
public static extern int DwmExtendFrameIntoClientArea(
    IntPtr hwnd,
    ref MARGINS pMarInset);

 

  创建方法ExtendAeroGlass 方法,可将WPF Window窗口的Aero Glass 区域扩展。

private void ExtendAeroGlass(Window window)
{
    try
    {
        
// 为WPF程序获取窗口句柄
         IntPtr mainWindowPtr
= new WindowInteropHelper(window).Handle;
        HwndSource mainWindowSrc
= HwndSource.FromHwnd(mainWindowPtr);
        mainWindowSrc.CompositionTarget.BackgroundColor
= Colors.Transparent;

        
// 设置Margins
        MARGINS margins
= new MARGINS();

        
// 扩展Aero Glass
        margins.cxLeftWidth
= -1;
        margins.cxRightWidth
= -1;
        margins.cyTopHeight
= -1;
        margins.cyBottomHeight
= -1;

        
int hr = DwmExtendFrameIntoClientArea(mainWindowSrc.Handle, ref margins);
        
if (hr < 0)
        {
            MessageBox.Show(
"DwmExtendFrameIntoClientArea Failed");
        }
    }
    catch (DllNotFoundException)
    {
        Application.Current.MainWindow.Background
= Brushes.White;
    }
}

 

  简单制作一个WPF 界面。

<Window x:Class="WpfAeroGlass.MainWindow"
        xmlns
="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x
="http://schemas.microsoft.com/winfx/2006/xaml"
        Title
="MainWindow" Height="350" Width="525">
    
<Grid x:Name="layout">
        
<Button x:Name="btn" Content="Button" Margin="191,66,202,211" />
        
<CheckBox x:Name="checkBox" Content="Extend AeroGlass"
                  Click
="CheckBox_Checked" Height="24" Width="121" />
    
</Grid>
</Window>

 

  补充CheckBox 点击事件,在其中启用ExtendAeroGlass 方法。

private void CheckBox_Checked(object sender, RoutedEventArgs e)
{
    
if (checkBox.IsChecked.Value)
    {
        this.Background
= Brushes.Transparent;
        ExtendAeroGlass(this);
    }
    
else
    {
        this.Background
= Brushes.White;
    }
}

 

  演示效果

  运行程序后,默认界面状态。

1
 

  点击"Extend AeroGlass" 选框,界面中 也将呈现玻璃效果。

1
 

  Windows API

  通过Windows API Code Pack 可以对Aero Glass 效果进行开启或关闭。在程序中加入Microsoft.WindowsAPICodePack.Shell 命名空间,调整AeroGlassCompositioinEnabled 完成开/关Aero Glass的效果。

  源代码

  WpfAeroGlass.zip

0
相关文章