How can I detect, or be notified, when windows is logging out in python?
Edit: Martin v. Löwis’ answer is good, and works for a full logout but it does not work for a ‘fast user switching’ event like pressing win+L which is what I really need it for.
Edit: im not using a gui this is running as a service
You can detect fast user switching events using the Terminal Services API, which you can access from Python using the
win32tsmodule from pywin32. In a GUI application, call WTSRegisterSessionNotification to receive notification messages, WTSUnRegisterSessionNotification to stop receiving notifications, and handle theWM_WTSSESSION_CHANGEmessage in your window procedure.If you’re writing a Windows service in Python, use the
RegisterServiceCtrlHandlerExfunction to detect fast user switching events. This is available in the pywin32 library as theRegisterServiceCtrlHandlerfunction in theservicemanagermodule. In your handler function, look for theSERVICE_CONTROL_SESSIONCHANGEnotification. See also theWM_WTSSESSION_CHANGEdocumentation for details of the specific notification codes.There’s some more detail in this thread from the python-win32 mailing list, which may be useful.
I hope this helps!