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:
…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.