disable or lock mouse and keyboard in Python?

Solution 1:

I haven't tested (actually I've tested the mouse part, and it annoyingly works) but something like this using pyhook would do what you want:

import pythoncom, pyHook 

def uMad(event):
    return False

hm = pyHook.HookManager()
hm.MouseAll = uMad
hm.KeyAll = uMad
hm.HookMouse()
hm.HookKeyboard()
pythoncom.PumpMessages()

Solution 2:

I have extended Fábio Diniz's answer to a class which provides both a block() and an unblock() function which block (selectively) mouse/keyboard inputs. I also added a timeout functionality which (hopefully) addresses the annoyance of locking oneself out.

import pyHook 
from threading import Timer
import win32gui
import logging

class blockInput():
    def OnKeyboardEvent(self,event):
        return False

    def OnMouseEvent(self,event):
        return False

    def unblock(self):
        logging.info(" -- Unblock!")
        if self.t.is_alive():
            self.t.cancel()
        try: self.hm.UnhookKeyboard()
        except: pass
        try: self.hm.UnhookMouse()
        except: pass

    def block(self, timeout = 10, keyboard = True, mouse = True):
        self.t = Timer(timeout, self.unblock)
        self.t.start()

        logging.info(" -- Block!")
        if mouse:
            self.hm.MouseAll = self.OnMouseEvent
            self.hm.HookMouse()
        if keyboard:
            self.hm.KeyAll = self.OnKeyboardEvent
            self.hm.HookKeyboard()
        win32gui.PumpWaitingMessages()

    def __init__(self):
        self.hm = pyHook.HookManager()

if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO)

    block = blockInput()
    block.block()

    import time
    t0 = time.time()
    while time.time() - t0 < 10:
        time.sleep(1)
        print(time.time() - t0)

    block.unblock()
    logging.info("Done.")

You can have a look at the main routine for example usage.

Solution 3:

For me, just two lines of programming solved the problem:

from ctypes import *

ok = windll.user32.BlockInput(True) #enable block

#or 

ok = windll.user32.BlockInput(False) #disable block 

Solution 4:

Totally different take since all the solutions mentioned above use a quiet outdated library(pyhook) and this pyhook method personally didnt work for me.

import keyboard
from pynput.mouse import Controller
from time import sleep

def blockinput():
    global block_input_flag
    block_input_flag = 1
    t1 = threading.Thread(target=blockinput_start)
    t1.start()
    print("[SUCCESS] Input blocked!")
    

def unblockinput():
    blockinput_stop()
    print("[SUCCESS] Input unblocked!")
    

    def blockinput_start():
        mouse = Controller()
        global block_input_flag
        for i in range(150):
            keyboard.block_key(i)
        while block_input_flag == 1:
            mouse.position = (0, 0)
    
    def blockinput_stop():
        global block_input_flag
        for i in range(150):
            keyboard.unblock_key(i)
        block_input_flag = 0


blockinput()
print("now blocking")
sleep(5)
print("now unblocking")

Solution 5:

I just slightly modified the @Robert code and instead of the time I used external interrupt to close the program i.e. if you connect any external drive then the program gets close and your mouse and keyboard will be working perfectly.

import pyHook 
from threading import Timer
import win32gui
import logging
import win32file

def locate_usb():#this will check any external Drives
    drive_list = []
    drivebits = win32file.GetLogicalDrives()
    # print(drivebits)
    for d in range(1, 26):
        mask = 1 << d
        if drivebits & mask:
            # here if the drive is at least there
            drname = '%c:\\' % chr(ord('A') + d)
            t = win32file.GetDriveType(drname)
            if t == win32file.DRIVE_REMOVABLE:
            drive_list.append(drname)
    return drive_list

class blockInput():
    def OnKeyboardEvent(self,event):
        return False

    def OnMouseEvent(self,event):
        return False

    def unblock(self):

        try: self.hm.UnhookKeyboard()
        except: pass
        try: self.hm.UnhookMouse()
        except: pass

    def block(self ,keyboard = True, mouse = True):
    
        while(1):
            if mouse:
                  self.hm.MouseAll = self.OnMouseEvent
                  self.hm.HookMouse()
            if keyboard:
                  self.hm.KeyAll = self.OnKeyboardEvent
                  self.hm.HookKeyboard()
            win32gui.PumpWaitingMessages()
            cg= locate_usb()
            if cg:
                break
      

    def __init__(self):
        self.hm = pyHook.HookManager()

if __name__ == '__main__':
    block = blockInput()
    block.block()
    block.unblock()

I hope this code will help you