简体   繁体   中英

MouseHook to detect when mouse is moving

I am trying to create a simple mouse hook to detect if the mouse is moving, but for some reason when I run the program, the mouse doesnt function at all until I stop the process.

Here is my code:

#include <windows.h>

HHOOK g_hMouse;

LRESULT CALLBACK MouseHook(int nCode, WPARAM wParam, LPARAM lParam)
{
    printf("MOUSE EVENT!\n");

    return CallNextHookEx(NULL, nCode, wParam, lParam);
}

int main()
{
    g_hMouse = SetWindowsHookEx(WH_MOUSE_LL, MouseHook, NULL, NULL);

    while (1) {
        Sleep(2);
    }

    return 0;
}

Any help would be appreciated.

Thanks.

WM_MOUSE_LL hooks require that the thread that installed it keeps pumping messages; so you'll need a GetMessage/DispatchMessage loop here. Details for this are in the MSDN docs for WM_MOUSE_LL :

This hook is called in the context of the thread that installed it. The call is made by sending a message to the thread that installed the hook. Therefore, the thread that installed the hook must have a message loop.

If you just want to try something quick when experimenting/debugging, replace your Sleep() with a call to MessageBox(...) , which will block your code so you can do testing, but it runs its own message loop, so the hook will run.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM