pythonpysimpleguipyhook

lock keys and release keys based on a button press using PySimpleGUI and pyhook


I have created a program where the user get access to the system keys such as ctrl and alt only with exiting a program with a button press. However when i run the program it does get stuck in the UI and wont allow me to do anything. Where am i wrong in this? Thanks in advance.

import PySimpleGUI as sg
import pyWinhook
import pythoncom

layout=[[sg.Button('Exit')]]
        
def blockKeys(event):
    if event.Key.lower() in ['lwin', 'tab', 'lmenu']:
        return False    # block these keys
    else:
        # return True to pass the event to other handlers
        return True

def releaseKeys(event):
    return True
        
window = sg.Window('Window Title', layout, no_titlebar=True, location=(0,0), size=(800,600), keep_on_top=True).Finalize()
window.Maximize()
hm = pyWinhook.HookManager()
hm.MouseAll = releaseKeys
hm.KeyAll = blockKeys
hm.HookMouse()
hm.HookKeyboard()
pythoncom.PumpMessages()

while True:
    event,values = window.read()
    print(event,values)
    
    if event =='Exit':
        hm = pyWinhook.HookManager()
        hm.MouseAll = releaseKeys
        hm.KeyAll = releaseKeys
        hm.HookMouse()
        hm.HookKeyboard()
        pythoncom.PumpMessages()
        break;

window.close()

Solution

  • pythoncom.PumpMessages() just sits idle and waits for Windows events. It means it will keep waiting there and do nothing. You use while loop in PySimpleGUI, so it is not necessary.

    code revised as following,

    import PySimpleGUI as sg
    import pyWinhook
    import pythoncom
    
    layout=[[sg.Button('Exit')]]
    
    def blockKeys(event):
        if event.Key.lower() in ['lwin', 'tab', 'lmenu']:
            return False    # block these keys
        else:
            # return True to pass the event to other handlers
            return True
    
    def releaseKeys(event):
        return True
    
    window = sg.Window('Window Title', layout, return_keyboard_events=True , finalize=True)
    hm = pyWinhook.HookManager()
    hm.MouseAll = releaseKeys
    hm.KeyAll = blockKeys
    hm.HookMouse()
    hm.HookKeyboard()
    # pythoncom.PumpMessages()
    
    while True:
        event,values = window.read()
        print(event,values)
    
        if event =='Exit':
            hm = pyWinhook.HookManager()
            hm.MouseAll = releaseKeys
            hm.KeyAll = releaseKeys
            hm.HookMouse()
            hm.HookKeyboard()
            # pythoncom.PumpMessages()
            break;
    
    window.close()