Windows 7 作業系統預設具有一款半透明效果主題(Aero Glass)。如果選擇了該款主題,所有的應用程式標題欄都會處於玻璃透明效果(如)。這個功能是由Desktop Window Manager(DWM)服務支援的。
預設情況下,我們編寫的應用程式在Windows 7 中也只有標題列和視窗架構會具備半透明效果,其他地區仍是不透明狀態(如)。如果想將程式整體都改為IE 視窗的效果,可以使用DWM API 將玻璃地區進行擴充。
首先,從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; }}
示範效果
運行程式後,預設介面狀態。
點擊"Extend AeroGlass" 選框,介面中<Grid> 也將呈現半透明效果。
Windows API
通過Windows API Code Pack 可以對Aero Glass 效果進行開啟或關閉。在程式中加入Microsoft.WindowsAPICodePack.Shell 命名空間,調整AeroGlassCompositioinEnabled 完成開/關Aero Glass的效果。
GlassWindow.AeroGlassCompositionEnabled = checkBox.IsChecked.Value;
原始碼
WpfAeroGlass.zip