关于C#:SetWindowsHookEx for WH_MOUSE

SetWindowsHookEx for WH_MOUSE

我手上有一些代码可以全局打印鼠标坐标(使用WH_MOUSE_LL)。我的目标是使用WH_MOUSE而不是WH_MOUSE_LL,因为(从我的阅读中)它更快。我已经阅读了论坛的内容,在使用WH_MOUSE时,需要在DLL中声明它以实现全局效果,但是仍然,当在程序中使用时,它应该在声明它的那个应用程序上起作用,但是它不起作用(仅将WH_MOUSE_LL更改为WH_MOUSE时不打印任何内容)。这是代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#define _WIN32_WINNT 0x0400
#pragma comment( lib,"user32.lib" )

#include <windows.h>
#include <stdio.h>

HHOOK hMouseHook;

LRESULT CALLBACK mouseProc (int nCode, WPARAM wParam, LPARAM lParam)
{
    MOUSEHOOKSTRUCT * pMouseStruct = (MOUSEHOOKSTRUCT *)lParam;
    if (pMouseStruct != NULL){
        if(wParam == WM_LBUTTONDOWN)
        {
            printf("clicked" );
        }
        printf("Mouse position X = %d  Mouse Position Y = %d\
"
, pMouseStruct->pt.x,pMouseStruct->pt.y);
    }
    return CallNextHookEx(hMouseHook, nCode, wParam, lParam);
}

DWORD WINAPI MyMouseLogger(LPVOID lpParm)
{
    HINSTANCE hInstance = GetModuleHandle(NULL);

    // here I put WH_MOUSE instead of WH_MOUSE_LL
    hMouseHook = SetWindowsHookEx( WH_MOUSE_LL, mouseProc, hInstance, NULL );

    MSG message;
    while (GetMessage(&message,NULL,0,0)) {
        TranslateMessage( &message );
        DispatchMessage( &message );
    }

    UnhookWindowsHookEx(hMouseHook);
    return 0;
}

int main(int argc, char** argv)
{
    HANDLE hThread;
    DWORD dwThread;

    hThread = CreateThread(NULL,NULL,(LPTHREAD_START_ROUTINE)MyMouseLogger, (LPVOID) argv[0], NULL, &dwThread);
    if (hThread)
        return WaitForSingleObject(hThread,INFINITE);
    else
        return 1;

}


1
2
// here I put WH_MOUSE instead of WH_MOUSE_LL
hMouseHook = SetWindowsHookEx( WH_MOUSE_LL, mouseProc, hInstance, NULL );

第四参数也必须更改为GetCurrentThreadId()才能使其本地化。


由于其中有一个" main",我的猜测是,您需要将其放入dll中,以便它可以处理* _LL类型以外的消息。

了解底层的鼠标和键盘挂钩(win32)

http://developer-resource.blogspot.com/2008/07/setwindowshookex-example.html具有dll示例