While you were sleeping…

I just came across an interesting use case which I thought I’d share – why let your application churn away doing unnecessary processing if the user isn’t paying attention?

So I started looking into detecting whether the workstation is locked, or if the screensaver is running – two fairly reliable ways of telling that the user has gone walkabout…

To detect a locked workstation, you need to listen out for:

Microsoft.Win32.SystemEvents.SessionSwitch

…which fires each time the user locks or unlocks the workstation.

To detect the state of the screensaver, you have to do slightly more work – there are no helpful events – instead you need some sort of polling mechanism to call away to a Win32 function:

private const int SPI_GETSCREENSAVERRUNNING = 0x0072;
[DllImport("user32.dll", SetLastError=true)]
static extern bool SystemParametersInfo(int action, int param, ref int retval, int updini);

int active = 1;
SystemParametersInfo(SPI_GETSCREENSAVERRUNNING, 0, ref active, 0);
bool screenSaverActive = (active == 1);

So I stitched these 2 bits of logic together into a nice helper class and now I can tell (within reason) when my users are there or not, and give our servers a break every now and then.

Advertisements

Leave a comment

Filed under UI Hints, Useful, Winforms, WPF

Leave a Reply

Please log in using one of these methods to post your comment:

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