Click here to Skip to main content
Click here to Skip to main content
Add your own
alternative version
Go to top

Another Screensaver with WPF

, 27 Jan 2012
Lessons learnt from writing a screensaver with WPF
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Media;

namespace RZWScreenSaver{
    public class GlassHelper{
        readonly Window window;
        readonly Win32.MARGINS margin;

        public GlassHelper(Window window) : this(window, new Thickness(-1)) {}
        public GlassHelper(Window window, Thickness margin){
            this.window = window;
            this.margin = new Win32.MARGINS(margin);
        }
        /// <summary>
        /// Repeat call may cause unexpected behavior!
        /// </summary>
        /// <returns></returns>
        public bool ExtendGlassFrame(){
            var isVistable = Environment.OSVersion.Version.Major >= 6;
            if (!isVistable || !DwmIsCompositionEnabled())
                return false;
            var hwnd = new WindowInteropHelper(window).Handle;
            if (hwnd == IntPtr.Zero)
                throw new InvalidOperationException("The Window must be shown before extending glass.");
            window.Background = Brushes.Transparent;

            var hwndSource = HwndSource.FromHwnd(hwnd);
            Debug.Assert(hwndSource != null);
            hwndSource.CompositionTarget.BackgroundColor = Colors.Transparent;

            var marginParam = margin;
            DwmExtendFrameIntoClientArea(hwnd, ref marginParam);

            hwndSource.AddHook(wndProc);

            return true;
        }
        IntPtr wndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled){
            if (msg == DwmCompositionChanged){
                ExtendGlassFrame();
                handled = true;
            }
            return IntPtr.Zero;
        }
        const int DwmCompositionChanged = 0x031E;
        [DllImport("dwmapi.dll", PreserveSig = false)]
        static extern void DwmExtendFrameIntoClientArea(IntPtr hWnd, ref Win32.MARGINS pMarInset);
        [DllImport("dwmapi.dll", PreserveSig = false)]
        static extern bool DwmIsCompositionEnabled();
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Common Development and Distribution License (CDDL)

Share

About the Author

Ruxo Zheng
Technical Lead
Thailand Thailand
C/C++ and C# programmer.

| Advertise | Privacy | Mobile
Web02 | 2.8.140916.1 | Last Updated 27 Jan 2012
Article Copyright 2009 by Ruxo Zheng
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid