Python块键盘/鼠标输入 [英] Python Block Keyboard / Mouse Input

查看:22
本文介绍了Python块键盘/鼠标输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试编写一个简短的脚本,它将在用户观看时进行摇摆(打开YouTube链接),并且不会干扰用户。 我已经设法逐个字母缓慢地打开插入链接,现在正试图阻止用户输入。 我尝试使用ctypes导入来阻止所有输入,运行脚本,然后再次取消阻止,但不知何故它不会阻止输入。我刚收到我的运行错误消息。 我如何修复它,这样输入就会被阻止? 提前谢谢! 代码如下:

import subprocess
import pyautogui
import time
import ctypes
from ctypes import wintypes

BlockInput = ctypes.windll.user32.BlockInput
BlockInput.argtypes = [wintypes.BOOL]
BlockInput.restype = wintypes.BOOL

blocked = BlockInput(True)

if blocked:
    try:
        subprocess.Popen(["C:\Program Files\Google\Chrome\Application\chrome.exe",])
        time.sleep(3)
        pyautogui.write('www.youtube.com/watch?v=DLzxrzFCyOs', interval= 0.5)
        pyautogui.hotkey('enter')
    finally:
        unblocked = BlockInput(False)
else:
    raise RuntimeError('Input is already blocked by another thread')

推荐答案

您可以使用键盘模块阻止所有键盘输入,并使用鼠标模块不断移动鼠标,以防止用户移动鼠标。

有关更多详细信息,请参阅以下链接:

https://github.com/boppreh/keyboard

https://github.com/boppreh/mouse

这会阻止键盘上的所有键(150的大小足以确保阻止所有键)。

#### Blocking Keyboard ####
import keyboard

#blocks all keys of keyboard
for i in range(150):
    keyboard.block_key(i)

这可以通过不断将鼠标移动到位置(1,0)来有效地阻止鼠标移动。

#### Blocking Mouse-movement ####
import threading
import mouse
import time

global executing
executing = True

def move_mouse():
    #until executing is False, move mouse to (1,0)
    global executing
    while executing:
        mouse.move(1,0, absolute=True, duration=0)

def stop_infinite_mouse_control():
    #stops infinite control of mouse after 10 seconds if program fails to execute
    global executing
    time.sleep(10)
    executing = False

threading.Thread(target=move_mouse).start()

threading.Thread(target=stop_infinite_mouse_control).start()
#^failsafe^

然后是您的原始代码(不再需要If语句和Try/Catch块)。

#### opening the video ####
import subprocess
import pyautogui
import time

subprocess.Popen(["C:\Program Files\Google\Chrome\Application\chrome.exe",])
time.sleep(3)
pyautogui.write('www.youtube.com/watch?v=DLzxrzFCyOs', interval = 0.5)
pyautogui.hotkey('enter')


#### stops moving mouse to (1,0) after video has been opened
executing = False

仅有几点注意事项:

  1. 程序外很难停止移动鼠标(程序执行时基本不可能关闭,尤其是键盘也被阻塞),这就是为什么我设置了故障保护,10秒后停止将鼠标移动到(1,0)。
  2. (在Windows上)Control-Alt-Delete允许打开任务管理器,然后可以从那里强制停止程序。
  3. 这不会阻止用户单击鼠标,有时会阻止完整键入YouTube链接(即可以打开新选项卡)

请在此处查看代码的完整版本:

https://pastebin.com/WUygDqbG

这篇关于Python块键盘/鼠标输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆