Starting and stopping the screensaver in C# can be done by calling the Windows API's PostMessage function, which posts a message to the Windows Message Queue asynchronously. Starting it is straight forward. But stopping it is somewhat tricky. I accomplished this here by stopping the window on the foreground which will always be the screensaver if it is running.
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern int PostMessage(
IntPtr hWnd, int wMsg, int wParam, int lParam);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr GetForegroundWindow();
private const Int32 WM_SYSCOMMAND = 0x112;
private const Int32 SC_SCREENSAVE = 0xF140;
private const int WM_CLOSE = 16;
public mainForm()
{
InitializeComponent();
}
private void callScreensaverButton_Click(object sender, EventArgs e)
{
// Start the screen saver.
PostMessage(this.Handle, WM_SYSCOMMAND, SC_SCREENSAVE, 0);
disableScreenSaverTimer.Enabled = true;
}
private void disableScreenSaverTimer_Tick(object sender, EventArgs e)
{
//close the application foreground
PostMessage(GetForegroundWindow(), WM_CLOSE, SC_SCREENSAVE, 0);
disableScreenSaverTimer.Enabled = false;
}