9

How can I check whether a Windows OS workstation is locked? (e.g. Win+L or choosing the lock option after Ctrl+Alt+Del.)

I want something like ctypes.windll.user32.isWorkstationLocked().

2
  • What version of Windows is it? Commented Dec 29, 2015 at 16:41
  • does any of below answers worked..?? Commented May 21, 2020 at 14:33

10 Answers 10

13

This code worked today for me on four different Windows 7 and 10 machines, try something similar:

import ctypes
import time
user32 = ctypes.windll.User32
time.sleep(5)
#
#print(user32.GetForegroundWindow())
#
if (user32.GetForegroundWindow() % 10 == 0): print('Locked')
# 10553666 - return code for unlocked workstation1
# 0 - return code for locked workstation1
#
# 132782 - return code for unlocked workstation2
# 67370 -  return code for locked workstation2
#
# 3216806 - return code for unlocked workstation3
# 1901390 - return code for locked workstation3
#
# 197944 - return code for unlocked workstation4
# 0 -  return code for locked workstation4
#
else: print('Unlocked')

Edit: Also, this one works today:

import subprocess
import time
time.sleep(5)
process_name='LogonUI.exe'
callall='TASKLIST'
outputall=subprocess.check_output(callall)
outputstringall=str(outputall)
if process_name in outputstringall:
    print("Locked.")
else: 
    print("Unlocked.")
5
  • 1
    Code from the edit section works for Windows 10 Pro like a charm.
    – Phoenix
    Commented Jul 31, 2019 at 10:26
  • 1
    Edit code works great. I assume the sleep is just so you have time to lock the screen and test.
    – Ruben
    Commented Jan 22, 2021 at 9:37
  • 2
    @Ruben, yes exactly for that. Glad it works for you!
    – macok
    Commented Jan 23, 2021 at 15:17
  • 1
    the original user32 doesn't work for me - it sometimes reports as locked even if it is not. Windows 10 Pro Commented Jan 20, 2022 at 21:38
  • This answer is incorrect. Other windows such as magnifier (Win+U) can become the foreground window while Windows 10 is locked.
    – Budd
    Commented Aug 19, 2022 at 7:27
6

A hack I discovered to get around to see if Windows 10 is locked is to look at the running processes using psutil. You then search to see whether or not LogonUI.exe is running. This process only runs when a user has a locked session.

Note: If you use "switch users" this process will be shown as running and this workaround will not work. Windows actually spawns multiple LogonUI.exe processes, one per logged on locked user. It is only useful when there is only one person logged on at a time.

import psutil

for proc in psutil.process_iter():
    if(proc.name() == "LogonUI.exe"):
        print ("Locked")
5

You can get the window on top, when the session is locked, the function return 0.

import ctypes
user32 = ctypes.windll.User32

def isLocked():
    return user32.GetForegroundWindow() == 0
2
  • 4
    This is false for me in Windows 10 Pro. When locked, the hwnd process ID is a changing number with the title "Windows Default Lock Screen". It's only hwnd == 0 when I press Enter to put the password in. I used a few lines from this example to fetch the title and compare it to either 0, "", or the title above. pixomania.net/programming/…
    – James Koss
    Commented Oct 13, 2018 at 13:34
  • @JamesKoss try the solution below this one, it worked for me.
    – Dani
    Commented Dec 19, 2018 at 3:49
3

Something like this should do the trick:

import time
import ctypes

user32 = ctypes.windll.User32
OpenDesktop = user32.OpenDesktopA
SwitchDesktop = user32.SwitchDesktop
DESKTOP_SWITCHDESKTOP = 0x0100

while 1:
  hDesktop = OpenDesktop ("default", 0, False, DESKTOP_SWITCHDESKTOP)
  result = SwitchDesktop (hDesktop)
  if result:
    print "Unlocked"
    time.sleep (1.0)
  else:
    print time.asctime (), "still locked"
    time.sleep (2)
2
  • 1
    @IvanBaksheev, are you using Python 3? This should be written to use OpenDesktopW and the explicit unicode literal u"Default".
    – Eryk Sun
    Commented Dec 30, 2015 at 22:31
  • Note that the "Default" desktop may not be the active application desktop, so switching to it is a side effect. I don't know how to get the current application desktop. OpenInputDesktop tries to open the active desktop, but that could be "Winlogon" if the workstation is locked (requires SYSTEM). It's not telling us what the WindowStation's active application desktop is. winlogon.exe tracks this, but I don't know an API to query it.
    – Eryk Sun
    Commented Dec 30, 2015 at 22:32
2

Hi Check these 4 lines..

returns the application name which is on the screen.. if window is locked returns the string - Windows Default Lock Screen.

from win32gui import GetWindowText, GetForegroundWindow
import time
time.sleep(5)
# lock the system or open the application for a check
print(GetWindowText(GetForegroundWindow()))
2
  • This answer is incorrect. Other windows such as magnifier (Win+U) can become the foreground window while Windows 10 is locked.
    – Budd
    Commented Aug 19, 2022 at 4:50
  • For other locale, the returned string could be different.
    – Rockallite
    Commented Nov 9, 2022 at 7:27
1

From the LockWorkStation() documentation:

There is no function you can call to determine whether the workstation is locked.

Not a Python limitation, but the system itself.

1

What works for me on Windows 10 Pro is getting the foreground window:

whnd = win32gui.GetForegroundWindow()
(_, pid) = win32process.GetWindowThreadProcessId(whnd)
handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, False, pid)
filename = win32process.GetModuleFileNameEx(handle, 0)
window_text = win32gui.GetWindowText(whnd)

This returns Windows Default Lock Screen as window title and C:\Windows\SystemApp\Microsoft.LockApp_<randomcharacters>\LockApp.exe as filename when locked.

However, as James Koss mentioned, GetForeGroundWindow will return 0 if the user is typing their password. There are also other (non-locked) situations where the current ForegroundWindow is 0, so this cannot be relied upon.

1
  • This answer is incorrect. Other windows such as magnifier (Win+U) can become the foreground window while Windows 10 is locked.
    – Budd
    Commented Aug 19, 2022 at 4:50
0

Based on @Stardidi answer, this worked for me (Windows 10 Pro):

import time
import win32gui
import win32api
import win32con
import win32process

while True:
    time.sleep(1)
    _, pid = win32process.GetWindowThreadProcessId(win32gui.GetForegroundWindow())

    try:
        handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, False, pid)
        filename = win32process.GetModuleFileNameEx(handle, 0)
    except Exception as _e:
        filename = "LockApp.exe"
        del _e

    current_status = "locked" if "LockApp" in filename else "unlocked"
0

There is no easy answer here, but you can do this via Session Tracking.

From the LockWorkStation() documentation:

There is no function you can call to determine whether the workstation is locked. To receive notification when the user logs in, use the WTSRegisterSessionNotification function to receive WM_WTSSESSION_CHANGE messages. You can use session notifications to track the desktop state so you know whether it is possible to interact with the user.

Begin by registering session notifications to a window of your program.

def register(handle: HWND) -> bool:
    """
    @param handle: handle for your message window.
    When registered, Windows Messages related to session event changes will be
    sent to the message window.
    @returns: True is session tracking is successfully registered.

    Blocks until Windows accepts session tracking registration.

    Every call to this function must be paired with a call to unregister.

    https://learn.microsoft.com/en-us/windows/win32/api/wtsapi32/nf-wtsapi32-wtsregistersessionnotification
    """
    # OpenEvent handle must be closed with CloseHandle.
    eventObjectHandle: HANDLE = ctypes.windll.kernel32.OpenEventW(
        # Blocks until WTS session tracking can be registered.
        # Windows needs time for the WTS session tracking service to initialize.
        # must ensure that the WTS session tracking service is ready before trying to register
        SYNCHRONIZE,  # DWORD dwDesiredAccess
        False,  # BOOL bInheritHandle - sub-processes do not need to inherit this handle
        # According to the docs, when the Global\TermSrvReadyEvent global event is set,
        # all dependent services have started and WTSRegisterSessionNotification can be successfully called.
        # https://learn.microsoft.com/en-us/windows/win32/api/wtsapi32/nf-wtsapi32-wtsregistersessionnotification#remarks
        "Global\\TermSrvReadyEvent"  # LPCWSTR lpName - The name of the event object.
    )
    if not eventObjectHandle:
        error = ctypes.WinError()
        log.error("Unexpected error waiting to register session tracking.")
        return False

    registrationSuccess = ctypes.windll.wtsapi32.WTSRegisterSessionNotification(handle, NOTIFY_FOR_THIS_SESSION)
    ctypes.windll.kernel32.CloseHandle(eventObjectHandle)

    if registrationSuccess:
        log.debug("Registered session tracking")
    else:
        error = ctypes.WinError()
        if error.errno == RPC_S_INVALID_BINDING:
            log.error(
                "WTS registration failed. "
                "Waited successfully on TermSrvReadyEvent to ensure that WTS is ready to allow registration. "
                "Cause of failure unknown. "
            )
        else:
            log.error("Unexpected error registering session tracking.")

    return registrationSuccess


def unregister(handle: HWND) -> None:
    """
    This function must be called once for every call to register.
    If unregistration fails, session tracking may not work properly until the session can be unregistered in a new instance.

    https://learn.microsoft.com/en-us/windows/win32/api/wtsapi32/nf-wtsapi32-wtsunregistersessionnotification
    """
    if ctypes.windll.wtsapi32.WTSUnRegisterSessionNotification(handle):
        log.debug("Unregistered session tracking")
    else:
        error = ctypes.WinError()
        log.error("Unexpected error unregistering session tracking.")

In your Window Message handler for the window, when you receive WM_WTSSESSION_CHANGE, handle WTS_SESSION_UNLOCK and WTS_SESSION_LOCK events to track the state of Windows being locked.

A similar answer here might give more context on handling windows messages.

0

Try to use the second proposed approach from the macok's answer (usage of the subprocess library). At least it is the only way in which I managed to solve the same problem...

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.