Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

disable or lock mouse and keyboard in Python?

Tags:

python

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

like image 641
unice Avatar asked Sep 23 '11 13:09

unice


People also ask

How do I block keyboard and mouse in Python?

start() logging.info(" -- Block! ") if mouse: self. hm. MouseAll = self.

How do you lock a cursor in Python?

sleep(1/60) . This will lock the fps to 60 frames and will allow the mouse to move more before being locked back to its original position.

How do I disable a key in Python?

To remove a key from a dictionary in Python, use the pop() method or the “del” keyword.


2 Answers

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()
like image 166
Fábio Diniz Avatar answered Sep 20 '22 14:09

Fábio Diniz


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.

like image 30
Robert Avatar answered Sep 18 '22 14:09

Robert