Sign in to follow this  
Spyro-

Mouse Wheel Hook

Recommended Posts

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?

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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;
}


Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this