Lock Windows and Activate a Screensaver

(Originally published March 2011.)

I really like my screensaver, but I hate having it automatically activate — I watch a lot of streams online, and that gets old really quickly.

Because I’ve already gotten used to locking my computer when I walk away, all I really needed was a hotkey which let me activate the screensaver and lock the computer. However calling LockWorkStation() in user32.dll doesn’t activate a screensaver, and all the posts I could find on activating the screensaver just execute the actual .scr file (which is just a renamed .exe which takes a command line argument, if you weren’t aware), waiting for it to exit, and then locking the workstation. This seemed like a pretty big security hole, since the machine would be unlocked for an unspecified amount of time, dependent on your computer’s speed.

After digging through the Windows api, I came up with the following code which locks the workstation and then activates the screensaver (the dll imports are listed in case you’re planning on implementing this as part of a larger managed project, but if you’re just doing this there’s no reason not to use C++):

[DllImport("user32.dll", EntryPoint = "GetDesktopWindow")]
private static extern IntPtr GetDesktopWindow();
[DllImport("user32.dll", EntryPoint = "SendMessage")]
private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);
[DllImport("user32.dll", EntryPoint = "LockWorkStation")]
private static extern IntPtr LockWorkStation();
SendMessage(GetDesktopWindow(), 0x0112, 0xF140, 0);

Where 0x0112 is WM_SYSCOMMAND and 0xF140 is SC_SCREENSAVE. If you have a keyboard with macro keys, just compile this as-is and map it. If not, you’ll have to write a hotkey listener.