如何在ctypes中使用鼠标/键盘钩子的结构信息

时间:2011-04-28 21:00:22

标签: python c dll struct ctypes

所以我有一些看起来像这样的c代码:

#pragma comment(linker, "/SECTION:.SHARED,RWS")
#pragma data_seg(".SHARED")
HMODULE hInstance = 0;
HHOOK hKeyboardHook = 0;
int lastKey = 0;
int keyFlags = 0;

HHOOK hMouseHook = 0;
int mouseMsgID = 0;
MOUSEHOOKSTRUCT *mHookPt;
MOUSEHOOKSTRUCT mHookStruct;

#pragma data_seg()

BOOL WINAPI DllMain(HANDLE hModule, DWORD dwFunction, LPVOID lpNot)
{
    hInstance = hModule;
    return TRUE;
}

LRESULT CALLBACK KeyboardProc(int hookCode, WPARAM vKeyCode, LPARAM flags)
{
    if(hookCode < 0)
    {
        return CallNextHookEx(hKeyboardHook, hookCode, vKeyCode, flags);
    }

    if(!hookCode)
    {
        lastKey = (int)vKeyCode;
        keyFlags = (int)flags;
    }

    return CallNextHookEx(hKeyboardHook, hookCode, vKeyCode, flags);
}

LRESULT CALLBACK MouseProc(int hookCode, WPARAM msgID, LPARAM pMouseHookStruct)
{
    if(hookCode < 0)
    {
        return CallNextHookEx(hMouseHook, hookCode, msgID, pMouseHookStruct);
    }

    if(!hookCode)
    {
        mouseMsgID = (int)msgID;
        mHookPt = (MOUSEHOOKSTRUCT *)pMouseHookStruct;
        mHookStruct = *mHookPt;
    }
    return CallNextHookEx(hMouseHook, hookCode, msgID, pMouseHookStruct);
}

__declspec(dllexport) int getLastKey(void)
{
    if(!lastKey)
        return 0;
    return lastKey;
}

__declspec(dllexport) int getLastFlags(void)
{
    if(!keyFlags)
        return 0;
    return keyFlags;
}

__declspec(dllexport) int getMsgID(void)
{
    if(!mouseMsgID)
        return 0;
    return mouseMsgID;
}

__declspec(dllexport) MOUSEHOOKSTRUCT getMouseStruct(void)
{
    return mHookStruct;
}

__declspec(dllexport) void InstallHooks(void)
{
    hKeyboardHook = SetWindowsHookEx(WH_KEYBOARD, KeyboardProc, hInstance, 0);
    hMouseHook = SetWindowsHookEx(WH_MOUSE, MouseProc, hInstance, 0);
}

__declspec(dllexport) void UninstallHooks(void)
{
    UnhookWindowsHookEx(hKeyboardHook);
    hKeyboardHook = 0;
    lastKey = 0;
    keyFlags = 0;

    UnhookWindowsHookEx(hMouseHook);
    mouseMsgID = 0;
    mHookPt = NULL;

}

它被编译成一个dll,使用ctypes.CDLL('blah.dll')加载到python中:

class MouseHookStruct(ctypes.wintypes.Structure):

    _fields_ = [("pt", ctypes.wintypes.POINT),
             ("hwnd", ctypes.wintypes.HWND),
             ("dwExtraInfo", ctypes.wintypes.POINTER(ctypes.wintypes.c_ulong))]

dll = ctypes.CDLL('blah.dll')
dll.getMouseStruct.restype = MouseHookStruct
try:
    dll.InstallHooks()
    mStruct = MouseHookStruct()
    while True:
        mStruct = dll.getMouseStruct()
        print mStruct.pt.x, mStruct.pt.y
except KeyboardInterrupt:
    pass
finally:
    dll.UninstallHooks()

所有这一切都打印出0 0,无论鼠标在哪里。键盘钩子很好,因为它的回调proc不使用结构。但是,如果我尝试WH_KEYBOARD_LL我有同样的问题(结构的所有值都是0)。在OS,C和Pythons ctypes之间传递结构时我错过了什么?

0 个答案:

没有答案