Can I get global mouse event on Unity using MSLLHOOKSTRUCT

  c++, unity3d, windows

First and foremost, I am a complete beginner, I apologies in advance if I’m not clear enough and I truly thank you for taking the time to read this!

I’m working on unity on a way to create a global mouse event tracker in order to record the inputs from the mouse event when the window isn’t in focus. There is a library called UnityRawInput that allows you to get global inputs in unity just like what I want, but for the keyboard.

The program in c# first sets the hook (which I think I nailed for the mouse, but not to sure about that) and then calls a function HandleLowLevelHookProc which allow to get the wParam and lParam from the function CallNextHookEx to get keys and their states like that :


    var kbd = KBDLLHOOKSTRUCT.CreateFromPtr(lParam);
    var keyState = (RawKeyState)wParam;
    var key = (RawKey)kbd.vkCode;

For each key switch, the functions HandleKeyDown and HandleKeyUp are informed of the switch and by adding listeners, you can know what key is being pressed or released (or at least that’s how I think that works), HandleKeyDown is for example as follows :


    private static void HandleKeyDown (RawKey key)
    {
        var added = pressedKeys.Add(key);
        if (added && OnKeyDown != null) OnKeyDown.Invoke(key);
    }

So my question is the following, can I modify that script to get the same behavior with the mouse, which is for example having the debug log recognize the clicks outside of the player.
I’ve tried naively to modify the code as such, which didn’t work of course :


    var ms = MSLLHOOKSTRUCT.CreateFromPtr(lParam);
    var keyState = (RawKeyState)wParam;
    var key = (RawKey)ms.mouseData;    

I’ve changed the RawKeyState so that the identifier of the mouse message is coherent with the values provided here : https://docs.microsoft.com/en-us/previous-versions/windows/desktop/legacy/ms644986(v=vs.85)

I think that my problem resides in my lack of understanding of the global mouse structure : https://docs.microsoft.com/fr-fr/windows/win32/api/winuser/ns-winuser-msllhookstruct

I honestly have no idea how much information I need to provide, if you have any hint or recommendation or if I’m completely lost, feel free to tell me 😀

Source: Windows Questions

LEAVE A COMMENT