unice
unice

Reputation: 2842

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.

Upvotes: 26

Views: 55497

Answers (7)

ProblemsLoop
ProblemsLoop

Reputation: 530

Since 2018, you can now use pynput (v1.4+) to suppress keyboard and mouse events on Windows, Mac, and Linux.

import pynput

# Disable mouse and keyboard events
mouse_listener = pynput.mouse.Listener(suppress=True)
mouse_listener.start()
keyboard_listener = pynput.keyboard.Listener(suppress=True)
keyboard_listener.start()

# Enable mouse and keyboard events
mouse_listener.stop()
keyboard_listener.stop()

This also disables mouse scrolling and clicking.

However, this does not stop users from pressing Ctrl+Alt+Del on Windows. But you can run the script in an elevated command prompt, and the mouse and keyboard will still be disabled, even if they opened Task Manager using Ctrl+Alt+Delete, so there is no harm done (apparently there are way to actually prevent Ctrl+Alt+Delete, but do your own research for that)

Upvotes: 8

Fighter178
Fighter178

Reputation: 413

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.

Upvotes: 0

Augurkenplukker12
Augurkenplukker12

Reputation: 155

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

Upvotes: 7

A rehman arjunagi
A rehman arjunagi

Reputation: 29

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

Upvotes: 2

F&#225;bio Diniz
F&#225;bio Diniz

Reputation: 10353

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

Upvotes: 29

Luciano Correa
Luciano Correa

Reputation: 149

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 

Upvotes: 14

Robert
Robert

Reputation: 1631

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.

Upvotes: 16

Related Questions