C/C++教程

Prevent screen saver from running by simulate keyboard events using windows API

本文主要是介绍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 key, which has no impact to input.

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 screen saver from running by simulate keyboard events using windows API的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!