Skip to content Skip to sidebar Skip to footer

Disable Or Lock Mouse And Keyboard In Python?

Is there a way of disabling or locking mouse and keyboard using python? I want to freeze the mouse and disable the keyboard.

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 

defuMad(event):
    returnFalse

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

classblockInput():
    defOnKeyboardEvent(self,event):
        returnFalsedefOnMouseEvent(self,event):
        returnFalsedefunblock(self):
        logging.info(" -- Unblock!")
        if self.t.is_alive():
            self.t.cancel()
        try: self.hm.UnhookKeyboard()
        except: passtry: self.hm.UnhookMouse()
        except: passdefblock(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
fromtime 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 = 0blockinput()
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

deflocate_usb():#this will check any external Drives
    drive_list = []
    drivebits = win32file.GetLogicalDrives()
    # print(drivebits)for d inrange(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

classblockInput():
    defOnKeyboardEvent(self,event):
        returnFalsedefOnMouseEvent(self,event):
        returnFalsedefunblock(self):

        try: self.hm.UnhookKeyboard()
        except: passtry: self.hm.UnhookMouse()
        except: passdefblock(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:
                breakdef__init__(self):
        self.hm = pyHook.HookManager()

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

I hope this code will help you

Post a Comment for "Disable Or Lock Mouse And Keyboard In Python?"