Home > C# > How To Disable Windows Screensaver programmatically?

How To Disable Windows Screensaver programmatically?


In some cases you may want to prevent Windows screensaver from running. For example, when a customer watch video or does VoIP call, his mouse and keyboard activities are low.

I didn’t find a managed function in .NET Framework but fortunately we can make it through PInvoke.

1. Add PInvoke namespace:

using System.Runtime.InteropServices;

2. Import SystemParametersInfo function and its enums as below:

public enum SPI : uint
{
   SPI_GETSCREENSAVEACTIVE = 0x0010,
   SPI_SETSCREENSAVEACTIVE = 0x0011
}

public enum SPIF : uint
{
   None = 0x00,
   SPIF_UPDATEINIFILE = 0x01,
   SPIF_SENDCHANGE = 0x02,
   SPIF_SENDWININICHANGE = 0x02
}

[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SystemParametersInfo(SPI uiAction, uint uiParam, ref uint pvParam, SPIF fWinIni);

[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SystemParametersInfo(SPI uiAction, uint uiParam, uint pvParam, SPIF fWinIni);
 3. You may want to check is screensaver enabled by Control panel setting or not:
uint vParam = 0;
if (SystemParametersInfo(SPI.SPI_GETSCREENSAVEACTIVE, 0, ref vParam, SPIF.None))
{
   if (vParam == 1)
       MessageBox.Show("Screensaver is enabled");
   else
        MessageBox.Show("Screensaver is disabled");
}
else
    MessageBox.Show("Error!");
 4. And finally - disable it:
if (SystemParametersInfo(SPI.SPI_SETSCREENSAVEACTIVE, 0, 0, SPIF.None))
{
   MessageBox.Show("Screensaver has been disabled");
}
else
    MessageBox.Show("Error!");
 5. Don’t forget to re-enable if it was enabled initially:
SystemParametersInfo(SPI.SPI_SETSCREENSAVEACTIVE, 1, 0, SPIF.None);
[From http://zayko.net]
Categories: C#
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: