Python 块键盘/鼠标输入

时间:2021-01-20 01:42:34

标签: python input block

我目前正在尝试编写一个简短的脚本,该脚本将在用户观看时进行 rickroll(打开 youtube 链接)并且无法干扰。 我已经设法逐个字母缓慢地打开插入链接,现在正在尝试阻止用户输入。 我曾尝试使用 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')

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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

查看这些链接了解更多详情:

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