WPF Glass Background

This example shows how to add the Vista/7 glass background to the application main frame:

 

Link: http://msdn.microsoft.com/en-us/library/ms748975.aspx

 

Here’s a source class which simplifies this example for reusability:

 

[StructLayout(LayoutKind.Sequential)]
public struct Margins
{
    public int LeftWidth;
    public int RightWidth;
    public int TopHeight;
    public int BottomHeight;
}

internal class GlassBackground
{
    [DllImport("DwmApi.dll")]
    public static extern int DwmExtendFrameIntoClientArea(IntPtr windowHandle, ref Margins marginInset);

    public static bool SetGlassBackground(Window window, FrameworkElement topBar)
    {
        try
        {
            IntPtr windowHandle = new WindowInteropHelper(window).Handle;
            HwndSource windowHandleSource = HwndSource.FromHwnd(windowHandle);
            windowHandleSource.CompositionTarget.BackgroundColor = Color.FromArgb(0, 0, 0, 0);

            Graphics desktop = Graphics.FromHwnd(windowHandle);
            float dpiX = desktop.DpiX;
            float dpiY = desktop.DpiY;

            Margins margins = new Margins
            {
                LeftWidth = Convert.ToInt32(5 * (dpiX / 96)),
                RightWidth = Convert.ToInt32(5 * (dpiX / 96)),
                TopHeight = Convert.ToInt32(((int)topBar.ActualHeight + 5) * (dpiX / 96)),
                BottomHeight = Convert.ToInt32(5 * (dpiX / 96)),
            };

            int extend = DwmExtendFrameIntoClientArea(windowHandleSource.Handle, ref margins);

            return extend >= 0;
        }
        catch (DllNotFoundException)
        {
            return false;
        }
    }
}

And to use this class on Window_Loaded event call as follows:

 

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    GlassBackground.SetGlassBackground(this, MainGrid);

Where MainGrid is the main grid of the window.

 

Here’s a screenshot of my app with Glassbackground (Window Color purple, on Windows 7)

 

image

 

Advertisements

About vijayvepa

I'm a software consultant for Software Specialists Inc. currently working at Philips Respironics, Pittsburgh

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: