Python – Monitoring a displays state in python


How can I tell when Windows is changing a monitors power state?

Best Solution

It seems that, when Windows wants to start the screen saver or turn the monitor off, it will send a WM_SYSCOMMAND to the topmost window with a wParam of SC_SCREENSAVE (to start the screen saver) or a wParam of SC_MONITORPOWER and a lParam of 1 or 2 (to turn the monitor off). This message will then be passed to DefWindowProc, which will actually do the action. So, if your window happens to be the topmost one, you can intercept these events and ignore them (or do anything else you want before passing them to DefWindowProc).

On Windows Vista, there seems to be a more intuitive, and more reliable, way to know the monitor power state. You call RegisterPowerSettingNotification to tell the system to send your window a WM_POWERBROADCAST message with a wParam of PBT_POWERSETTINGCHANGE and a lParam pointing to a POWERBROADCAST_SETTING structure.

I cannot test either of them since I currently do not have any computer with Windows nearby. I hope, however, they point you in the right direction.