Search code examples
c#wpfcallbacksetwindowshookexglobal-hotkey

SetWindowsHookEx not working properly


I have tried to make a global mousehotkey with SetWindowsHookEx() so when I press the right mouse button it executes some code. My problem is that when the callback function gets executed, it gives me a weird number for the right button that keeps changing everytime the code gets executed.

private static IntPtr ButtonHookCallback(int nCode, IntPtr wParam, IntPtr lParam)
    {

        int button = Marshal.ReadInt32(lParam);
        if (nCode >= 0 && wParam == (IntPtr)WM_RBUTTONDOWN)
        {
            if (button == 0x02)
            {
                _m.rtbLog.AppendText("Test");
            }

        }

        return CallNextHookEx(MainWindow._hookId, nCode, wParam, lParam);
    }

When I read lParam it gives me like a number around 600 and changes everytime the code gets executed even though it should be 0x2. How can I fix this :P.

EDIT: It works perfectly when I do it with keys


Solution

  • 0x02 means WM_MOUSEMOVE, which should come from wParam rather lParam. The lParam means MOUSEHOOKSTRUCT, which will frequently change as for containing x- and y-coordinates of the cursor. Just refer to [MouseProc callback function][1] and [MOUSEHOOKSTRUCT structure][2]