Vista/Windows 7 的 Aero Glass 效果讓視窗邊框呈現半透明磨砂質感。預設僅非客戶區(標題列、邊框)啟用,若希望整個視窗客戶區皆為玻璃效果,需呼叫 DWM API DwmExtendFrameIntoClientArea。網路多為 Windows Forms 範例,WPF 的 Window 類別無直接 Handle 屬性,需額外步驟取得視窗控制代碼並設定背景透明。
SourceInitialized 事件後(確保 Handle 已建立)執行。WindowInteropHelper 取得 IntPtr hwnd。window.Background = Brushes.Transparent;
HwndSource.FromHwnd(hwnd).CompositionTarget.BackgroundColor = Colors.Transparent;
MARGINS 結構,呼叫 DwmExtendFrameIntoClientArea(hwnd, margins)。若 margin 為 Thickness(-1) 表示整個客戶區延伸。public partial class Window1 : System.Windows.Window
{
public Window1() { InitializeComponent(); }
protected override void OnSourceInitialized(EventArgs e)
{
base.OnSourceInitialized(e);
DWMLib.AeroHelper.ExtendGlassFrame(this, new Thickness(-1));
}
}
public class AeroHelper
{
public static bool ExtendGlassFrame(Window window, Thickness margin)
{
if (!DwmApi.DwmIsCompositionEnabled()) return false;
IntPtr hwnd = new WindowInteropHelper(window).Handle;
if (hwnd == IntPtr.Zero)
throw new InvalidOperationException("The Window must be shown before extending glass.");
window.Background = Brushes.Transparent;
HwndSource.FromHwnd(hwnd).CompositionTarget.BackgroundColor = Colors.Transparent;
DWMLib.DwmApi.MARGINS margins = new DWMLib.DwmApi.MARGINS(
(int)margin.Left, (int)margin.Top, (int)margin.Right, (int)margin.Bottom);
DwmApi.DwmExtendFrameIntoClientArea(hwnd, margins);
return true;
}
}
public class DwmApi
{
[DllImport("dwmapi.dll", PreserveSig = false)]
public static extern void DwmExtendFrameIntoClientArea(IntPtr hWnd, MARGINS pMargins);
[DllImport("dwmapi.dll", PreserveSig = false)]
public static extern bool DwmIsCompositionEnabled();
// 其他 DWM API 宣告略...
[StructLayout(LayoutKind.Sequential)]
public class MARGINS
{
public int cxLeftWidth, cxRightWidth, cyTopHeight, cyBottomHeight;
public MARGINS(int left, int top, int right, int bottom)
{
cxLeftWidth = left; cyTopHeight = top; cxRightWidth = right; cyBottomHeight = bottom;
}
}
// RECT, DWM_BLURBEHIND, DWM_THUMBNAIL_PROPERTIES 結構略...
}
SourceInitialized 之後呼叫,否則 hwnd 為零會拋出例外。DwmIsCompositionEnabled 回傳 false,需優雅降級。
透過 P/Invoke 呼叫 dwmapi.dll 並正確設定 WPF 視窗背景,即可在 WPF 應用程式中實現整個視窗的 Aero Glass 效果,打造現代化、視覺吸引力的使用者介面。