Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I lock the screen using C#?

Tags:

c#

screen

locking

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.

like image 872
dole doug Avatar asked Oct 19 '09 11:10

dole doug


2 Answers

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.

like image 88
Joey Avatar answered Sep 21 '22 13:09

Joey


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.

e.g.

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).

like image 43
Iain Collins Avatar answered Sep 18 '22 13:09

Iain Collins