简体   繁体   中英

How can I lock the screen using C#?

I just write my first C# application, which is a scheduler. Once an hour I want to pop-up a dialog and lock the screen for two minutes in order to take a break.

As of now, my application just shows a form on "TopMost" when its time to break and hides it two minutes later.

How can I lock the screen as well? Something similar to the UAC style in Vista.

Eep, misread your question. The UAC dialog of Vista creates a new desktop and shows itself on that. To Create a desktop you can use the CreateDesktop function. You can then use SwitchDesktop to switch to it.

If you truly want to re-create the secure desktop's looks, then you need to take a screenshot first and display that on your form, darkened a little.


Original answer below, which might be of interest too:

Take a look at the LockWorkStation function.

However, you can't programmatically unlock the work station again. That's something the user has to do himself. So you can't easily enfore a break at least two minutes long unless you still resort to your top-level window technique to deny the user his workspace as long as the two minutes are not yet over.

As an alternative to taking a screen grab (which I've also used as an approach in the past under slightly different circumstances) you can also do this by creating a new window (WinForm) that is full screen and on top of all other windows.

If you set the window background colour to solid black then set the opacity to 70-80%, you'll get something that looks like the UAC prompt.

eg

formName.WindowState = FormWindowState.Maximized; 
formName.FormBorderStyle = FormBorderStyle.None; 
formName.Opacity = 0.70; 
formName.TopMost = true;

Of course it would be sensible to draw a window on top of this informing the user why the screen has been dimmed, with a counter.

Using something that looks enough like a UAC prompt (which people are accustomed to seeing) to not have people even think twice about it might be enough depending on the use case.

As with the screen grab approach, this on it's own does not prevent a user from bypassing it by using the Windows key, Alt - Tab or Ctrl - Esc to bring up the Start menu, or to switch to other tasks.

Disabling built in key commands requires setting Registry Keys relating to Windows Hotkeys and is a bit more tricky (I think it requires a reboot and can't be toggled on the fly).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM