Zayko in the Net

Personal blog of Vitaly Zayko


How to lock workstation programmatically? (C#)

There is no such .NET function (or at least I didn’t find). Fortunately we can use PInvoke instead.
Use this function to lock workstation’s display to protect from unauthorized use. Result of this function is the same as pressing Ctrl+Alt+Del.
  1. Add namespace at the top of your code:
    	using System.Runtime.InteropServices;
  2. Declare PInvoke:
    	[DllImport("user32.dll", SetLastError = true)]
    	static extern bool LockWorkStation();
  3. Call this function like this:
    	if (!LockWorkStation())
    	   throw new Win32Exception(Marshal.GetLastWin32Error());