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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 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()

Method 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.

Method 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

Method 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")

Method 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

Method 6

You can use pyautogui to do this. Though I recommend adding keyboard for making a stopping key. First, you want to install pyautogui and keyboard.
Please note: this only disables the mouse not the keyboard, that is a very bad idea.

pip install pyautogui
pip install keyboard

Ok, with that sorted, we have to actually make the disabler.

import pyautogui
import keyboard

stopKey = "s" #The stopKey is the button to press to stop. you can also do a shortcut like ctrl+s
maxX, maxY = pyautogui.size() #get max size of screen
While True:
    if keyboard.is_pressed(stopKey):
        break
    else:
    pyautogui.moveTo(maxX/2, maxY/2) #move the mouse to the center of the screen

Ok, but there is 2 ways to get out of this. pressing S, and also quickly moving the mouse to one of the corners of the screen (that is a pyautogui failsafe, but we can disable that). If you want to disable the failsafe, add this after the imports:

pyautogui.FAILSAFE = False

Please note that disabling the failsafe is NOT recommended!
Ok, so now the only way to exit is the S key. If you want to stop this somewhere else in your program, do this:

 pyautogui.press(stopKey)

Ok, so its not perfect, but it will stop you from doing basically anything with your mouse.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x