MouseHook 检测鼠标何时移动

MouseHook to detect when mouse is moving

我正在尝试创建一个简单的鼠标钩子来检测鼠标是否在移动,但是由于某些原因,当我 运行 程序时,鼠标根本不起作用,直到我停止该过程。

这是我的代码:

#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;
}

如有任何帮助,我们将不胜感激。

谢谢。

WM_MOUSE_LL 钩子要求安装它的线程不断发送消息;所以你需要一个 GetMessage/DispatchMessage 循环。有关详细信息,请参见 WM_MOUSE_LL:

的 MSDN 文档

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.

如果您只是想在 experimenting/debugging 时快速尝试一些事情,请将您的 Sleep() 替换为对 MessageBox(...) 的调用,这将阻止您的代码以便您进行测试,但它 运行 有自己的消息循环,所以钩子会 运行.