views:

250

answers:

1

How does one run screensaver within Windows Form as background for it? User also can interact with form controls while screensaver running.

[Why this?] We have a case which we need to run Windows Bubbles screensaver while user can continue interacting with form controls?

+1  A: 

You can use the following code :

    private void ShowScreenSaver(Control displayControl)
    {
        using (RegistryKey desktopKey = Registry.CurrentUser.OpenSubKey(@"Control Panel\Desktop"))
        {
            if (desktopKey != null)
            {
                string screenSaverExe = desktopKey.GetValue("SCRNSAVE.EXE") as string;
                if (!string.IsNullOrEmpty(screenSaverExe))
                {
                    Process p = Process.Start(screenSaverExe, "/P " + displayControl.Handle);
                    p.WaitForInputIdle();
                    IntPtr hwnd = p.MainWindowHandle;
                    if (hwnd != IntPtr.Zero)
                    {
                        SetParent(hwnd, displayControl.Handle);
                        Rectangle r = displayControl.ClientRectangle;
                        MoveWindow(hwnd, r.Left, r.Top, r.Width, r.Height, true);
                    }
                }
            }
        }
    }

    [DllImport("user32.dll")]
    static extern IntPtr SetParent(IntPtr hwndChild, IntPtr hwndParent);

    [DllImport("user32.dll")]
    static extern bool MoveWindow(IntPtr hwnd, int x, int y, int width, int height, bool repaint);

The parameter is the form or control in which you want to display the screensaver preview. Note that the screensaver will briefly appear in full screen before it is resized.

Thomas Levesque
Screensaver loaded successfully but coontrol is not resized, and screen saver continue running in full screen mode.
Ahmed
I use Panel as control to preview screen saver.
Ahmed
It's not the control that needs to be resized, only the window in which the screensaver runs. If you're using a panel, just pass the panel as the method argument. I'm using this code and it works fine (on Windows 7)
Thomas Levesque
I've two panels, one for controls and another one to preview screensaver, while screensaver is being loaded within its panel, it sets to be in full screen mode. Code runs on Windows Xp, any suggestion?
Ahmed
I don't have Windows XP available to check if it works the same... Did you try with different screensavers ? Not all of them support preview
Thomas Levesque
Yes, tried with different screensavers.
Ahmed
I tried this on Vista with 2 screens. It works somewhat, the entire screen goes black and then the Screensaver is resized to the Panel. It also runs on the second screen however. And it dies when the Mouse moves over the Panel or 2nd screen.
Henk Holterman