import time import threading import winsound from ctypes import * from ctypes.wintypes import * LRESULT=c_long HOOKPROC=WINFUNCTYPE(LRESULT,c_int,WPARAM,LPARAM) VK_RETURN=13 WM_QUIT=18 WH_KEYBOARD_LL=13 HC_ACTION=0 LLKHF_UP=128 class KBDLLHOOKSTRUCT(Structure): _fields_=[ ('vkCode',DWORD), ('scanCode',DWORD), ('flags',DWORD), ('time',DWORD), ('dwExtraInfo',DWORD), ] @HOOKPROC def keyHookFunc(code,wParam,lParam): if code!=HC_ACTION: return windll.user32.CallNextHookEx(0,code,wParam,lParam) kbd=KBDLLHOOKSTRUCT.from_address(lParam) if not (kbd.flags&LLKHF_UP) and kbd.vkCode!=VK_RETURN: winsound.Beep(770,70) return 1 return windll.user32.CallNextHookEx(0,code,wParam,lParam) def hookThreadFunc(): keyHookID=windll.user32.SetWindowsHookExW(WH_KEYBOARD_LL,keyHookFunc,windll.kernel32.GetModuleHandleW(None),0) if keyHookID==0: raise OSError("Could not register keyboard hook") msg=MSG() while windll.user32.GetMessageW(byref(msg),None,0,0): pass if windll.user32.UnhookWindowsHookEx(keyHookID)==0: raise OSError("could not unregister key hook %s"%keyHookID) if __name__=='__main__': print "Starting hook thread" hookThread=threading.Thread(target=hookThreadFunc) hookThread.start() print "The keyboard is hooked, characters except for enter should be blocked" buf=raw_input("Type some characters and press enter: ") if len(buf)==0: print "blocking was successful" else: print "Keys were not blocked" print "Sending quit message to hook thread" windll.user32.PostThreadMessageW(hookThread.ident,WM_QUIT,0,0) hookThread.join() print "done"