Wednesday, December 19, 2012

Prevent Screen Saver In WPF Application

Sometimes we want your application to be always visible, preventing the screen saver (or monitor off) to happen.

We can achieve this by calling an API of the OS.

First we have to declare the OS API:
[DllImport("kernel32.dll")]
private static extern uint SetThreadExecutionState(uint esFlags);
private const uint ES_CONTINUOUS = 0x80000000;
private const uint ES_SYSTEM_REQUIRED = 0x00000001;
private const uint ES_DISPLAY_REQUIRED = 0x00000002;

When the application starts (or any time you want to disable the screen saver):
SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED | ES_DISPLAY_REQUIRED);

When the application ends (or any time you want to enable the screen saver):
SetThreadExecutionState(ES_CONTINUOUS);

No comments:

Post a Comment