C# – How to invoke the screen saver in Windows in C#


I'd like to invoke the user's screen saver if such is defined, in a Windows environment.

I know it can be done using pure C++ code (and then the wrapping in C# is pretty simple), as suggested here.

Still, for curiosity, I'd like to know if such task can be accomplished by purely managed code using the dot net framework (version 2.0 and above), without p/invoke and without visiting the C++ side (which, in turn, can use windows API pretty easily).

Best Solution

I've an idea, I'm not sure how consistently this would work, so you'd need to research a bit I think, but hopefully it's enough to get you started.

A screen saver is just an executable, and the registry stores the location of this executable in HKCU\Control Panel\Desktop\SCRNSAVE.EXE

On my copy of Vista, this worked for me:

RegistryKey screenSaverKey = Registry.CurrentUser.OpenSubKey(@"Control Panel\Desktop");
if (screenSaverKey != null)
    string screenSaverFilePath = screenSaverKey.GetValue("SCRNSAVE.EXE", string.Empty).ToString();
    if (!string.IsNullOrEmpty(screenSaverFilePath) && File.Exists(screenSaverFilePath))
        Process screenSaverProcess = Process.Start(new ProcessStartInfo(screenSaverFilePath, "/s"));  // "/s" for full-screen mode
        screenSaverProcess.WaitForExit();  // Wait for the screensaver to be dismissed by the user