Prevent screen saver from running by simulate keyboard events using windows API
2022/4/6 7:21:21
本文主要是介绍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 screen saver from running by simulate keyboard events using windows API的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-15PingCAP 黄东旭参与 CCF 秀湖会议,共探开源教育未来
- 2024-05-13PingCAP 戴涛:构建面向未来的金融核心系统
- 2024-05-09flutter3.x_macos桌面os实战
- 2024-05-09Rust中的并发性:Sync 和 Send Traits
- 2024-05-08使用Ollama和OpenWebUI在CPU上玩转Meta Llama3-8B
- 2024-05-08完工标准(DoD)与验收条件(AC)究竟有什么不同?
- 2024-05-084万 star 的 NocoDB 在 sealos 上一键起,轻松把数据库编程智能表格
- 2024-05-08Mac 版Stable Diffusion WebUI的安装
- 2024-05-08解锁CodeGeeX智能问答中3项独有的隐藏技能
- 2024-05-08RAG算法优化+新增代码仓库支持,CodeGeeX的@repo功能效果提升