首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

WPF 完整啟用 Vista Aero Glass 效果:將玻璃擴展至整個視窗

     編輯:關於.NET

前言

Vista/Windows 7 的 Aero Glass 效果讓視窗邊框呈現半透明磨砂質感。預設僅非客戶區(標題列、邊框)啟用,若希望整個視窗客戶區皆為玻璃效果,需呼叫 DWM API DwmExtendFrameIntoClientArea。網路多為 Windows Forms 範例,WPF 的 Window 類別無直接 Handle 屬性,需額外步驟取得視窗控制代碼並設定背景透明。

核心步驟

  1. 於視窗 SourceInitialized 事件後(確保 Handle 已建立)執行。
  2. 透過 WindowInteropHelper 取得 IntPtr hwnd。
  3. 將 WPF 與 Win32 兩側背景皆設為透明:
    window.Background = Brushes.Transparent;
    HwndSource.FromHwnd(hwnd).CompositionTarget.BackgroundColor = Colors.Transparent;
    
  4. 定義 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));
    }
}

DWM API 封裝類別

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 為零會拋出例外。
  • 若系統未啟用桌面合成(DWM),DwmIsCompositionEnabled 回傳 false,需優雅降級。
  • 視窗內容需自行處理可讀性,因背景全透明可能導致文字難以辨識。

Aero Glass 全視窗效果圖

結語

透過 P/Invoke 呼叫 dwmapi.dll 並正確設定 WPF 視窗背景,即可在 WPF 應用程式中實現整個視窗的 Aero Glass 效果,打造現代化、視覺吸引力的使用者介面。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved