Daily Demo: Glass Effect in Windows 7

Ein schon etwas älteres Feature von Windows ist die Aero-Oberfläche. Ein Hingucker bei Aero sind die Fenster die vollständig durchsichtig sind. Standardmäßig sind die Titelleiste und die Ränder bei allen Anwendungen durchscheinend. Der eigentliche Inhalt jedoch nicht. Um dies in seine eigenen Anwendungen zu aktivieren ist sehr wenig Code notwendig.

 using System;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Media;

namespace Windows7Features
{
    public class Helper
    {
        [DllImport("dwmapi.dll", PreserveSig = false)]
        static extern void DwmExtendFrameIntoClientArea(IntPtr hwnd, ref MARGINS margins);

        [DllImport("dwmapi.dll", PreserveSig = false)]
        static extern bool DwmIsCompositionEnabled();

        public static bool ExtendGlassFrame(Window window, Thickness margin)
        {
            if (!DwmIsCompositionEnabled())
                return false;

            IntPtr hwnd = new WindowInteropHelper(window).Handle;
            if (hwnd == IntPtr.Zero)
                throw new InvalidOperationException("The Window must be shown before extending glass.");

            // Set the background to transparent from both the WPF and Win32 perspectives
            window.Background = Brushes.Transparent;
            HwndSource.FromHwnd(hwnd).CompositionTarget.BackgroundColor = Colors.Transparent;

            MARGINS margins = new MARGINS(margin);
            DwmExtendFrameIntoClientArea(hwnd, ref margins);
            return true;
        }
    }

    struct MARGINS
    {
        public MARGINS(Thickness t)
        {
            Left = (int)t.Left;
            Right = (int)t.Right;
            Top = (int)t.Top;
            Bottom = (int)t.Bottom;
        }
        public int Left;
        public int Right;
        public int Top;
        public int Bottom;
    }
}
Klasse Helper

Die Initialisierung des Fensters muss nach dem Laden des Fensters geschehen. Ein gutes Ereignis dafür ist das “Loaded”-Ereignis:

 using System.Windows;

namespace ASimpleGlassUi
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            this.Loaded += (s, e) =>
                {
                    Helper.ExtendGlassFrame(this, new Thickness(-1));
                };
        }

    }
}

Das Ergebnis sieht wie folgt aus:

image

Das bisschen Code ist hier zu finden: