Prevent screen saver from running by simulate keyboard events using windows API
作者:互联网
The condition of triggering screen saver to run is that no input event of any input device in a period of time.
The key idea is that we can simulate keyboard event periodically to prevent screen saver ro run.
The Windows API to simulate keyboard event is keybd_event:
void keybd_event(
BYTE bVk,
BYTE bScan,
DWORD dwFlags,
ULONG_PTR dwExtraInfo
);
API document can be found here: https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-keybd_event
To make it easy, we use python to implement it, a pre-requisite model "pywin32" should be installed first:
pip install pywin32
In addition to this, we must carefully choose a "save" key that to make sure this key will not affect user, we don't like any unexpected characters appear during our work. We use
Further more, we need to touch keyboard twice, the former to triggers WM_KEYUP, the later triggers WM_KEYDOWN, that's a whole keyboard event.
We must periodically trigger this keyboard event, its a simple polling model —— the progress of sleep for a while and awake to do something and repeat forever.
At last, to make our program behave user friendly, we setup signal handler for SIGINT and SIGTERM, in the handler we just print "bye !" and exit.
Let's see the code, you can also download it here: screen-on.py
import signal
import win32api
import win32con
import time
INTERVAL_SECS = 60
INTERVAL_SLEEP = 5
KB_VCODE = win32con.VK_SCROLL
def sigHandler(signum, frame):
print('byte !');
exit()
def setupSignalHandler():
signal.signal(signal.SIGINT, sigHandler)
signal.signal(signal.SIGTERM, sigHandler)
def touchKeyboard():
win32api.keybd_event(KB_VCODE, 0, 0, 0)
win32api.keybd_event(KB_VCODE, 0, win32con.KEYEVENTF_KEYUP, 0)
def main():
setupSignalHandler()
lastTicks = time.time()
while True:
ticks = time.time()
if (ticks - lastTicks > INTERVAL_SECS):
touchKeyboard()
lastTicks = ticks
print('touch at ', ticks);
time.sleep(INTERVAL_SLEEP)
if __name__ == '__main__':
main()
run it in command line box:
python screen-on.py
Hope you enjoy it, have fun
标签:Prevent,signal,windows,screen,keyboard,keybd,time,event 来源: https://www.cnblogs.com/labs798/p/16101843.html