在鼠标挂钩中,滚轮增量始终为 0

In mouse hooking, the wheel delta is always 0

#include <iostream>
#include <windows.h>

LRESULT CALLBACK mouseProc(int nCode, WPARAM wParam, LPARAM lParam){
  if(wParam == WM_MOUSEWHEEL){
    std::cout << "wheel: " << GET_WHEEL_DELTA_WPARAM(wParam) << std::endl;
  }else{
    MOUSEHOOKSTRUCT* mouselparam = (MOUSEHOOKSTRUCT*)lParam;
    std::cout << "etc: " << wParam << " - " << mouselparam->pt.x << "x" << mouselparam->pt.y << std::endl;
  }
  return CallNextHookEx(NULL, nCode, wParam, lParam);
}

int main(int argc, char *argv[]) {

    HHOOK hhkLowLevelMouse = SetWindowsHookEx(WH_MOUSE_LL, mouseProc, 0, 0);

    MSG msg;
    while (!GetMessage(&msg, NULL, NULL, NULL)) {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    UnhookWindowsHookEx(hhkLowLevelMouse);

    return 0;
}

这是完整代码。

“等:”完全符合我的预期。

"wheel:" 始终输出 0。

我是不是漏了什么?

使用 HIWORD 而不是 GET_WHEEL_DELTA_WPARAM 得到相同的结果。

GET_WHEEL_DELTA_WPARAM() 仅适用于真实 WM_MOUSEWHEEL window 消息的 wParam,不适用于 WH_MOUSE_LL 挂钩的 wParam

在钩子中,wParam 只是消息标识符本身,仅此而已。所有鼠标详细信息都存储在 lParam 指向的 MSLLHOOKSTRUCT 结构中。您试图查看除 WM_MOUSEWHEEL 以外的所有鼠标消息,但您查看的是错误的结构(MOUSEHOOKSTRUCTWH_MOUSE 使用, 而不是 WH_MOUSE_LL).

根据 LowLevelMouseProc callback function 文档:

  • wParam [in]
    Type: WPARAM

    The identifier of the mouse message. This parameter can be one of the following messages: WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MOUSEMOVE, WM_MOUSEWHEEL, WM_MOUSEHWHEEL, WM_RBUTTONDOWN, or WM_RBUTTONUP.

  • lParam [in]
    Type: LPARAM

    A pointer to an MSLLHOOKSTRUCT structure.

以及 MSLLHOOKSTRUCT structure 文档:

mouseData
Type: DWORD

If the message is WM_MOUSEWHEEL, the high-order word of this member is the wheel delta. The low-order word is reserved. A positive value indicates that the wheel was rotated forward, away from the user; a negative value indicates that the wheel was rotated backward, toward the user. One wheel click is defined as WHEEL_DELTA, which is 120.

试试这个:

LRESULT CALLBACK mouseProc(int nCode, WPARAM wParam, LPARAM lParam){
    if (nCode == HC_ACTION) {
        MSLLHOOKSTRUCT* mouselparam = (MSLLHOOKSTRUCT*)lParam;
        if (wParam == WM_MOUSEWHEEL) {
            short delta = HIWORD(mouselparam->mouseData); 
            // alternatively, GET_WHEEL_DELTA_WPARAM() would also work here:
            // short delta = GET_WHEEL_DELTA_WPARAM(mouselparam->mouseData);
            std::cout << "wheel: " << delta << std::endl;
        }else{
            std::cout << "etc: " << wParam << " - " << mouselparam->pt.x << "x" << mouselparam->pt.y << std::endl;
        }
    }
    return CallNextHookEx(NULL, nCode, wParam, lParam);
}