BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Windows Programming
.NET 1.1+

Locking the Workstation Programmatically

Microsoft Windows operating systems include the ability to lock the workstation. This leaves programs running but prevents access by unauthorised users, requiring a password to unlock the computer and continue working.

LockWorkStation API Function

Users of Microsoft Windows can lock their computer to prevent unauthorised access using the menu that appears when they press Ctrl-Alt-Delete, or by pressing the Windows key and L. This hides the currently executing applications and prevents further interaction with them until the workstation is unlocked using a password. You can recreate this function programmatically in a .NET application using Platform Invocation Services (P/Invoke) and the LockWorkStation API function.

LockWorkStation is a simple function that accepts no parameters and returns a Boolean value. The return value is true if the locking is successful and false if the computer cannot be locked. There are several reasons that locking may be unavailable, including:

  • The API function is called from a non-interactive program. It is possible to lock from interactive processes, such as Windows applications, but not from non-interactive processes, such as most Windows services.
  • No user has logged on to Windows yet.
  • The computer is already locked.

Using LockWorkStation

To use the LockWorkStation function you must first declare it. Before adding the code for the function, add the following using directive to simplify access to the P/Invoke attributes.

using System.Runtime.InteropServices;

We can now add the declaration of the API function to a class. If you are only using the API function from a single class you can declare it there. If it will be shared, you should create a separate class to contain API methods and change the declaration to make the method public or internal.

[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool LockWorkStation();

Finally, to lock the workstation we can call the function. In the code below the LockWorkStation method is called and its return value is checked by an if statement. If the result is true, no further action is necessary. If it is false, a message box is displayed, indicating that the locking attempt failed.

if (!LockWorkStation())
{
    MessageBox.Show("Unable to lock workstation");
}
14 November 2011