Windows hook with Python

Hey guys. I am trying to connect to windows and use Python to record keystrokes. For this, I use the LowLevelKeyboard callback procedure.

def run():

    global KeyBdHook
    global messages

    KeyBdHook = HHook()
    messages = []

    start = time.time()

    #Record keystrokes for 2 seconds.
    while time.time() < (start + 2):
        KeyBdHook.hook = SetWindowsHookEx(13, KeyboardProc,
                                          GetModuleHandle(0), 0)
        if KeyBdHook.hook == 0:
            print 'ERROR: '+str(ctypes.windll.kernel32.GetLastError())
        UnhookWindowsHookEx(KeyBdHook.hook)

    print messages

def KeyboardProc(nCode, wParam, lParam):
    """http://msdn.microsoft.com/en-us/library/ms644985(v=vs.85).aspx"""


    if nCode < 0:
        return ctypes.windll.user32.GetNextHookEx(KeyBdHook.hook,
                                              nCode, wParam, lParam)
    else:
        ctypes.windll.kernel32.RtlMoveMemory(ctypes.addressof(KeyBdHook.kStruct),
                                             ctypes.c_void_p(lParam),
                                             ctypes.sizeof(lParam))

        messages.append(KeyBdHook.kStruct)
        return ctypes.windll.user32.GetNextHookEx(KeyBdHook.hook,
                                          nCode, wParam, lParam)


def SetWindowsHookEx(idHook, lpFn, hMod, dwThreadId):
    WinFunc = ctypes.WINFUNCTYPE(c_ulong, c_ulong, c_ulong, c_ulong)
    return ctypes.windll.user32.SetWindowsHookExA(idHook, WinFunc(lpFn), hMod, dwThreadId)

def GetModuleHandle(lpModuleName):
    return ctypes.windll.kernel32.GetModuleHandleA(lpModuleName)

def UnhookWindowsHookEx(hHook):
    return ctypes.windll.user32.UnhookWindowsHookEx(hHook)

class HHook():        
    def __init__(self):
        self.hook = HHOOK
        self.kStruct = KBLLHOOKSTRUCT()

class KBLLHOOKSTRUCT(Structure):
    """http://msdn.microsoft.com/en-us/library/ms644967(v=vs.85).aspx"""

    _fields_ = [("vkCode", c_ulong),
                ("scanCode", c_ulong),
                ("flags", c_ulong),
                ("time", c_ulong),
                ("dwExtraInfo", POINTER(c_ulong))]

The problem is that it never enters the KeyboardProc function. I think that I may have to use it as a C-type function using ctypes.WINFUNCTYPE or ctypes.CFUNCTYPE, but I cannot figure it out. Windows does not seem to cause an error in SetWindowsEx either.

I assume that it does not process the KeyboardProc parameter passed to SetWindowsEx. Any ideas on how to do this so that Windows can enter data into it? Thank.

+5
source share
1

, ThiefMaster , dll , . - Python, , OP. Github.

, pyHook pyhk..

, pywinauto, .

+3

All Articles