See if my workstation is locked


The requirement: Wait until the workstation is unlocked before doing something. This might seem like a slightly odd requirement, but someone did in fact request it on the python-win32 list. In any case, it illustrates a small use of the Win32 Desktop functionality which would otherwise have gone unexplored (by me).

The approach relies on the fact that an attempt to switch to a desktop which is locked will fail. So, get a handle to the default desktop and try to switch to it. If you can't, wait a bit and try again.

import time
import ctypes

user32 = ctypes.windll.User32
OpenDesktop = user32.OpenDesktopA
SwitchDesktop = user32.SwitchDesktop

user32.LockWorkStation ()
# Slight pause to overcome what appears to
# be a grace period during which a switch
# *will* succeed.
time.sleep (1.0)

while 1:
  hDesktop = OpenDesktop ("default", 0, False, DESKTOP_SWITCHDESKTOP)
  result = SwitchDesktop (hDesktop)
  if result:
    print "Unlocked"
    print time.asctime (), "still locked"
    time.sleep (2)