Python阻止键盘/鼠标输入

4

我目前正在尝试编写一个短脚本,在用户观看时自动打开一个YouTube链接(rickroll),并且用户无法干扰。

我已经成功地逐字母缓慢插入链接,现在正在尝试阻止用户输入。

我尝试使用ctypes导入来阻止所有输入,运行脚本,然后再次解除阻止,但它似乎无法阻止输入。我只收到我的RuntimeError消息。

如何修复它,以便输入被阻止?

提前感谢!这是代码:

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')
3个回答

4
你可以使用键盘模块来阻止所有的键盘输入,使用鼠标模块来不断移动鼠标,以防止用户移动它。
请参阅以下链接以了解更多详细信息:

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上)Ctrl-Alt-Del可以打开任务管理器,然后从那里强制停止程序。
  3. 这不能阻止用户点击鼠标,有时会导致无法完全输入YouTube链接(即可能打开一个新的选项卡)。

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

https://pastebin.com/WUygDqbG


这无法阻止用户点击鼠标。有人有解决方案吗? - sighclone

1
你可以像这样做来阻止键盘和鼠标输入。
    from ctypes import windll
    from time import sleep
    
    windll.user32.BlockInput(True) #this will block the keyboard input
    sleep(15) #input will be blocked for 15 seconds
    windll.user32.BlockInput(False) #now the keyboard will be unblocked

嗨@señor.woofers,上面的代码对我来说不起作用,这段代码真的有效吗?你是否找到了解决问题的方法? - F Casian
1
只有以管理员身份运行时才能正常工作。大多数/所有与键盘或输入阻止相关的解决方案都需要管理员权限,这是您所期望的。 - hi im lost

0
这是一个用于阻止键盘和鼠标输入的函数。您可以向blockMouseAndKeys函数传递一个数字以调整超时时间:
import os
import time
import pyautogui
from threading import Thread
from keyboard import block_key

def blockMouseAndKeys(timeout=5):
    global blocking
    blockStartTime = time.time()
    pyautogui.FAILSAFE = False
    blocking = True
    try: float(timeout)
    except: timeout = 5

    def blockKeys(timeout):
        global blocking
        while blocking:
            if timeout:
                if time.time()-blockStartTime > timeout:
                    print(f'Keyboard block timed out after {timeout}s.')
                    return
            for i in range(150):
                try: block_key(i)
                except: pass
    def blockMouse(timeout):
        global blocking
        while blocking:
            def resetMouse(): pyautogui.moveTo(5,5)
            Thread(target=resetMouse).start()
            if timeout:
                if time.time()-blockStartTime > timeout:
                    print(f'Mouse block timed out after {timeout}s.')
                    return
    def blockTimeout(timeout):
        global blocking
        time.sleep(timeout)
        blocking = False
        pyautogui.FAILSAFE = False
        print('Done blocking inputs!')

    print('Blocking inputs...')
    Thread(target=blockKeys, args=[timeout]).start()
    Thread(target=blockMouse, args=[timeout]).start()
    Thread(target=blockTimeout, args=[timeout]).start()


blockMouseAndKeys(timeout=10)
os.startfile('https://www.youtube.com/watch?v=DLzxrzFCyOs')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接