Click here to Skip to main content
15,895,192 members
Articles / Desktop Programming / WPF

Another Screensaver with WPF

Rate me:
Please Sign up or sign in to vote.
4.87/5 (17 votes)
27 Jan 2012CDDL8 min read 72.2K   4.3K   63  
Lessons learnt from writing a screensaver with WPF
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;

namespace RZWScreenSaver{
    static class WindowExtension{
        static public void ActivateNextNotBottomMost(this Window w){
            var hwnd = new WindowInteropHelper(w).Handle;
            Debug.Assert(hwnd != IntPtr.Zero);

            var nextHwnd = Win32.GetWindow(hwnd, Win32.GW_HWNDNEXT);
            while(nextHwnd != hwnd){
                if (Win32.IsWindowVisible(nextHwnd) && ((Win32.GetWindowLong(nextHwnd, Win32.GWL_EXSTYLE) & Win32.WS_EX_NOACTIVATE) == 0)){
                    var canSet = Win32.SetForegroundWindow(nextHwnd);
                    Debug.Assert(canSet);
                    break;
                }
                nextHwnd = Win32.GetWindow(nextHwnd, Win32.GW_HWNDNEXT);
            }
        }
        static public void SetBottomMost(this Window w){
            var hwnd = new WindowInteropHelper(w).Handle;
            Debug.Assert(hwnd != IntPtr.Zero);
            Win32.SetWindowPos(hwnd, Win32.HWND_BOTTOM, 0, 0, 0, 0, Win32.SWP_NOSIZE | Win32.SWP_NOMOVE | Win32.SWP_NOACTIVATE);
        }
        static public void SetNoActivate(this Window w){
            var hwnd = new WindowInteropHelper(w).Handle;
            Debug.Assert(hwnd != IntPtr.Zero);
            var newValue = Win32.GetWindowLong(hwnd, Win32.GWL_EXSTYLE)|Win32.WS_EX_NOACTIVATE;
            var lastError = Marshal.GetLastWin32Error();
            Debug.Assert(lastError == 0, "GetWindowLong error " + lastError);
            Win32.SetWindowLong(hwnd, Win32.GWL_EXSTYLE, newValue);
            lastError = Marshal.GetLastWin32Error();
            Debug.Assert(lastError == 0, "SetWindowLong error " + lastError);
#if DEBUG
            var confirm = Win32.GetWindowLong(hwnd, Win32.GWL_EXSTYLE);
            Debug.Assert(newValue == confirm);
#endif
        }
    }
}

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)


Written By
Architect
Thailand Thailand
C/C++ and C# programmer.

Comments and Discussions