WPF 擴展玻璃效果(Aero Glass)

作者: Gnie  來源: 博客園  發布時間: 2010-10-09 18:01  閱讀: 5694 次  推薦: 0   原文鏈接   [收藏]  

  Windows 7 操作系統默認具有一款玻璃效果主題(Aero Glass)。如果選擇了該款主題,所有的應用程序標題欄都會處于玻璃透明效果(如下圖)。這個功能是由Desktop Window Manager(DWM)服務支持的。

GlassExample

  默認情況下,我們編寫的應用程序在Windows 7 中也只有標題欄和窗口框架會具備玻璃效果,其他區域仍是不透明狀態(如下圖)。如果想將程序整體都改為上圖IE 窗口的效果,可以使用DWM API 將玻璃區域進行擴展。

Notepad

  首先,從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;
    }
}

  演示效果

  運行程序后,默認界面狀態。

Default

  點擊"Extend AeroGlass" 選框,界面中<Grid> 也將呈現玻璃效果。

AllGlass

  Windows API

  通過Windows API Code Pack 可以對Aero Glass 效果進行開啟或關閉。在程序中加入Microsoft.WindowsAPICodePack.Shell 命名空間,調整AeroGlassCompositioinEnabled 完成開/關Aero Glass的效果。

GlassWindow.AeroGlassCompositionEnabled = checkBox.IsChecked.Value;

  源代碼:WpfAeroGlass.zip

0
0
 
標簽:WPF
 
 

文章列表

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()