17

I ran into this example for locking Windows workstation:

using System.Runtime.InteropServices;
...
[DllImport("user32.dll", SetLastError = true)]
static extern bool LockWorkStation();

...
if (!LockWorkStation())
    throw new Win32Exception(Marshal.GetLastWin32Error()); // or any other thing

Is there a pure managed alternative to this snippet? Namely, without P-Invoke.

Kara
  • 6,115
  • 16
  • 50
  • 57
Ron Klein
  • 9,178
  • 9
  • 55
  • 88

1 Answers1

20

No there is not. This is the best way to achieve this action.

Even if it was provided in the BCL, its implementation would almost certainly be identical to your sample. It's not something the CLR would natively implement.

InteXX
  • 6,135
  • 6
  • 43
  • 80
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • @RonKlein : Hey I want to does same thing. i.e programmatically Locking Windows Desktop and shows the Login screen without closing the session of the current user. This does same or something different??? thankx for your above solution it help me in many ways. Just make me clear above question. – Hemang Rami Feb 14 '12 at 11:08
  • @Hemang Rami, I think what you try to do is exactly what I was asking about: locking the workstation while keeping the current session active. – Ron Klein Feb 14 '12 at 12:19
  • @RonKlein: I had done it using LOCKWORKSTATION Method. is it ok now. ? I am not using rundll32.exe for locking Workstation. – Hemang Rami Feb 15 '12 at 07:02
  • @Hemang Rami, no problem. Just know that it works only on Windows OS. – Ron Klein Feb 15 '12 at 13:32
  • http://stackoverflow.com/questions/13745788/c-sharp-lockout-account#13745833 provides the solution! – Saw Dec 06 '12 at 14:39