8

Hopefully this is a simple one, but can anyone provide some simple c# code that will launch the currently configured screensaver?

Erik
  • 304
  • 2
  • 5
  • 10

1 Answers1

9

Here is a good site showing how to work with all aspects of the screensaver. See the comments at the end for the code to start the screensaver.

http://www.codeproject.com/KB/cs/ScreenSaverControl.aspx

    [DllImport("user32.dll", EntryPoint = "GetDesktopWindow")]
    private static extern IntPtr GetDesktopWindow();

    [DllImport("user32.dll")]
    private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);

    //...

    private const int SC_SCREENSAVE = 0xF140;
    private const int WM_SYSCOMMAND = 0x0112;

    //...

    public static void SetScreenSaverRunning()
    {
    SendMessage

(GetDesktopWindow(), WM_SYSCOMMAND, SC_SCREENSAVE, 0);
}
cfeduke
  • 23,100
  • 10
  • 61
  • 65
Inisheer
  • 20,376
  • 9
  • 50
  • 82
  • The PInvoke signature is incorrect. Both wParam and lParam should be typed to IntPtr – JaredPar Nov 06 '08 at 05:50
  • The code works with ints in the SendMessage for w and l params, but as its written the const ints will not work with IntPtrs. – cfeduke Nov 06 '08 at 05:56
  • Thanks for the change. Dont have an IDE on this computer to test. Putting good faith in the community and online content. Thanks again :-) – Inisheer Nov 06 '08 at 05:57
  • Argument '3': cannot convert from 'int' to 'System.IntPtr' - editing James' code back to ints, it ran correctly before IntPtr edits. – cfeduke Nov 06 '08 at 06:11
  • 1
    It runs correctly on a 32 bit machine but will fail miserably on a 64 bit one. – JaredPar Nov 06 '08 at 06:49
  • @cfeduke JaredPar is correct that wParam and lParam should be IntPtr. You need to explicitly cast the message codes to IntPtr in order to get rid of the compiler error. Example: (IntPtr)WM_SYSCOMMAND – Zach Johnson Jun 05 '09 at 21:17
  • Just to be cautious; do not forget to check if there is any screensaver is activated on the control panel. I had set "none" in my setting and it cost me 10 mins. to find out why the function doesn't work. – ozanmuyes Sep 26 '13 at 10:02