Python SetThreadExecutionState: How do I prevent screen display from turning off?

0

I am on Windows. I want to run a Python Script that involves keyboard activity hence my PC mustn't lock screen or go to sleep. Instead of changing my PC Sleep Setting, I want to use Python code to keep my Screen Display On for the whole duration of my Python Script.

I modified the code here Prevent sleep mode python (Wakelock on python) but it doesn't work. My screen display still offs automatically. MY modified code as below:

class WindowsInhibitor:
    '''Prevent OS sleep/hibernate in windows; code from:
    https://github.com/h3llrais3r/Deluge-PreventSuspendPlus/blob/master/preventsuspendplus/core.py
    API documentation:
    https://msdn.microsoft.com/en-us/library/windows/desktop/aa373208(v=vs.85).aspx'''
    ES_CONTINUOUS = 0x80000000
    ES_SYSTEM_REQUIRED = 0x00000001
    ES_DISPLAY_REQUIRED= 0x00000002
    
    def __init__(self):
        pass
    
    def inhibit(self):
        import ctypes
        print("Preventing Windows from going to sleep")
        ctypes.windll.kernel32.SetThreadExecutionState(
            WindowsInhibitor.ES_CONTINUOUS | \
            WindowsInhibitor.ES_DISPLAY_REQUIRED)
    
    def uninhibit(self):
        import ctypes
        print("Allowing Windows to go to sleep")
        ctypes.windll.kernel32.SetThreadExecutionState(
            WindowsInhibitor.ES_CONTINUOUS)

import os

osSleep = None
    # in Windows, prevent the OS from sleeping while we run
if os.name == 'nt':
    osSleep = WindowsInhibitor()              
    osSleep.inhibit()
python
ctypes
asked on Stack Overflow Nov 17, 2020 by pp12345

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0