3 Comments
  •   Posted in: 
  • C#
I recently needed to determine whether the workstation that an application was running on is locked. Surprisingly, I couldn't find anything really simple on the internet so I figured out my own little method of doing it. I've simplified the code into a static method so it really easy to call. The code is below:
[DllImport("user32", EntryPoint = "OpenDesktopA",
                     CharSet = CharSet.Ansi, 
                     SetLastError = true,
                     ExactSpelling = true)]
private static extern Int32 OpenDesktop(string lpszDesktop, 
                                        Int32 dwFlags, 
                                        bool fInherit,
                                        Int32 dwDesiredAccess);

[DllImport("user32", CharSet = CharSet.Ansi,
                     SetLastError = true, 
                     ExactSpelling = true)]
private static extern Int32 CloseDesktop(Int32 hDesktop);

[DllImport("user32", CharSet = CharSet.Ansi,
                     SetLastError = true,
                     ExactSpelling = true)]
private static extern Int32 SwitchDesktop(Int32 hDesktop);

public static bool IsWorkstationLocked()
{
  const int DESKTOP_SWITCHDESKTOP = 256;
  int hwnd = -1;
  int rtn = -1;

  hwnd = OpenDesktop("Default", 0, false, DESKTOP_SWITCHDESKTOP);

  if (hwnd != 0)
  {
    rtn = SwitchDesktop(hwnd);
    if (rtn == 0)
    {
      // Locked
      CloseDesktop(hwnd);
      return true;
    }
    else
    {
      // Not locked
      CloseDesktop(hwnd);
    }
  }
  else
  {
    // Error: "Could not access the desktop..."
  }
  return false;
}
Hope this helps anyone that comes across the same problem.

Comments

Comment by Hung

This doesn't work on Windows 10 when user presses Ctrl L to lock the machine.

Comment by Ashish

This code doesn't work on win10 devices, SwitchDesktop always succeeds even when it is in locked state.

Ashish
Post comment