Hello!
You can detect Windows lock and unlock events in Python by using the pywin32 library to interact with the Windows API. Below is a Python script that listens for session change notifications and detects when the user locks or unlocks the workstation.
First, make sure you have pywin32 installed:
pip install pywin32
Here is the Python code:
import win32api
import win32gui
import win32con
import win32ts
# Define session change constants
WTS_SESSION_LOGON = 0x5
WTS_SESSION_LOGOFF = 0x6
WTS_SESSION_LOCK = 0x7
WTS_SESSION_UNLOCK = 0x8
WTS_SESSION_REMOTE_CONNECT = 0x9
WTS_SESSION_REMOTE_DISCONNECT = 0xA
WTS_SESSION_CREATE = 0xB
WTS_SESSION_TERMINATE = 0xC
class SessionChangeMonitor:
def __init__(self):
# Register the window class
wc = win32gui.WNDCLASS()
wc.lpszClassName = 'SessionChangeMonitor'
wc.lpfnWndProc = self.wnd_proc # Window procedure
self.hInstance = wc.hInstance = win32api.GetModuleHandle(None)
self.classAtom = win32gui.RegisterClass(wc)
# Create the window
style = 0
self.hwnd = win32gui.CreateWindow(self.classAtom, 'SessionChangeMonitorWindow',
style,
0, 0, win32con.CW_USEDEFAULT,
win32con.CW_USEDEFAULT,
0, 0, self.hInstance, None)
# Register to receive session change notifications
win32ts.WTSRegisterSessionNotification(self.hwnd, win32ts.NOTIFY_FOR_THIS_SESSION)
def wnd_proc(self, hwnd, msg, wparam, lparam):
if msg == win32con.WM_WTSSESSION_CHANGE:
if wparam == WTS_SESSION_LOCK:
print("The session is locked.")
# Add your code here to handle the lock event
elif wparam == WTS_SESSION_UNLOCK:
print("The session is unlocked.")
# Add your code here to handle the unlock event
elif msg == win32con.WM_DESTROY:
# Unregister session notifications and quit the application
win32ts.WTSUnRegisterSessionNotification(self.hwnd)
win32gui.PostQuitMessage(0)
return win32gui.DefWindowProc(hwnd, msg, wparam, lparam)
if __name__ == '__main__':
monitor = SessionChangeMonitor()
print("Monitoring session lock/unlock events. Press Ctrl+C to exit.")
try:
win32gui.PumpMessages()
except KeyboardInterrupt:
print("Exiting...")
win32gui.DestroyWindow(monitor.hwnd)
Explanation:
-
Imports: The script imports necessary modules from pywin32.
-
Constants: It defines constants for different session change events.
-
SessionChangeMonitor Class:
- It creates a hidden window which can receive Windows messages.
- Registers for session notifications using
win32ts.WTSRegisterSessionNotification.
- Implements
wnd_proc method to handle Windows messages.
- In
wnd_proc, it checks for WM_WTSSESSION_CHANGE messages.
- If the session is locked (
WTS_SESSION_LOCK), it prints a message.
- If the session is unlocked (
WTS_SESSION_UNLOCK), it prints a message.
-
Main Execution:
- Creates an instance of
SessionChangeMonitor.
- Enters the message loop with
win32gui.PumpMessages().
- Handles
KeyboardInterrupt (Ctrl+C) to exit gracefully.
Usage:
-
Save the script to a file, e.g., session_monitor.py.
-
Run the script from the command line:
python session_monitor.py
-
The script will start monitoring for lock and unlock events.
-
Lock and unlock your Windows session to see the messages printed by the script.
Note:
-
The script runs indefinitely until you press Ctrl+C in the command line window where it is running.
-
You can add your own code in the places indicated in the script (comments in wnd_proc method) to perform actions when the session is locked or unlocked.
Dependencies:
- The script requires
pywin32, which can be installed via pip install pywin32.
Tested On:
- This script should work on Windows systems with Python 3.x and
pywin32 installed.
I hope this helps you detect Windows lock and unlock events in your Python application. Let me know if you have any questions or need further assistance!