views:

395

answers:

2

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.

+9  A: 

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

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

JaredPar
+1 for the clarification, thanks.
Ron Klein
A: 

This works well, I think:

ProcessStartInfo psi = new ProcessStartInfo("rundll32.exe");
psi.Arguments = "user32.dll, LockWorkStation";
Process.Start(psi);

It does pretty much the same thing as your P/Invoke sample, but without importing the function.

Fredrik Mörk
It might do the same thing, but I think the P/Invoke method is safer and carries far less overhead.
Scott Dorman
It's a workaround to P/Invoke. It's like a manual P/Invoke by invoking a different process. However, it's the closest solution to my question. Accepted.
Ron Klein
rundll32 isn't intended to be used to call arbitrary functions: http://blogs.msdn.com/oldnewthing/archive/2004/01/15/58973.aspx
Bradley Grainger