Zayko in the Net

Personal blog of Vitaly Zayko

NAVIGATION - SEARCH

C#: 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);

Add comment