Mouse Wheel Hook

Started by
2 comments, last by abort 15 years, 8 months ago
Hi. I'm doing a hook to detect mouse wheel movements:

#define _WIN32_WINDOWS 0x501
#define _WIN32_WINNT 0x0501
#include <windows.h>
#include <stdio.h>
//
HHOOK g_hMouseHook;
//
LRESULT CALLBACK LowLevelMouseProc(int nCode, WPARAM wParam, LPARAM lParam) {
  if (nCode >= 0) {
    if (wParam == WM_MOUSEWHEEL) {
      int zDelta = (short) HIWORD(wParam);
      printf("Wheel: %i\n", zDelta);
    }
  }
  return CallNextHookEx(g_hMouseHook, nCode, wParam, lParam);
}
//
int main() {
  MSG msg;
  g_hMouseHook = SetWindowsHookEx(WH_MOUSE_LL, LowLevelMouseProc, GetModuleHandle(NULL), 0);
  if (!g_hMouseHook) { printf("Error: %d\n", GetLastError()); }
  while(GetMessage(&msg, NULL, 0, 0)) {
    TranslateMessage(&msg);
    DispatchMessage(&msg);
  }
  UnhookWindowsHookEx(g_hMouseHook);
  return (int) msg.wParam;
}

This code detects well when the mouse wheel is moving, but the problem is that I can't detect the direction of the movement because zDelta is always zero. Any ideas?
Advertisement
The WPARAM you get in your hook procedure is not the same one youd get when handling the message. The WPARAM is the message. The WPARAM does not include anything else but the message. The delta will come from the MSLLHOOKSTRUCT in the LPARAM.
Thx. :-)

Fixed code:

#define _WIN32_WINDOWS 0x501#define _WIN32_WINNT 0x0501#include <windows.h>#include <stdio.h>//HHOOK g_hMouseHook;//LRESULT CALLBACK LowLevelMouseProc(int nCode, WPARAM wParam, LPARAM lParam) {  if (nCode >= 0) {    PMSLLHOOKSTRUCT pmll = (PMSLLHOOKSTRUCT) lParam;    if (wParam == WM_MOUSEWHEEL) {      int zDelta = (short) HIWORD(pmll->mouseData);      (zDelta > 0) ? printf("Wheel Up\n") : printf("Wheel Down\n");    }  }  return CallNextHookEx(g_hMouseHook, nCode, wParam, lParam);}//int main() {  MSG msg;  g_hMouseHook = SetWindowsHookEx(WH_MOUSE_LL, LowLevelMouseProc, GetModuleHandle(NULL), 0);  if (!g_hMouseHook) { printf("Error: %d\n", GetLastError()); }  while(GetMessage(&msg, NULL, 0, 0)) {    TranslateMessage(&msg);    DispatchMessage(&msg);  }  UnhookWindowsHookEx(g_hMouseHook);  return (int) msg.wParam;}
Nice that you fixed it, however I don't recommend you to use WH_MOUSE_LL... this lowlevel function utilizes much more cpu load than WH_MOUSE.

This topic is closed to new replies.

Advertisement