Search code examples
c#winapihook.net-4.5setwindowshookex

How to set SetWindowsHookEx only on a specific window to listen for mouse left button up events


I am trying to get when the left mouse button up is hapenning on a specific window. So I googled and find an interesting code snippet here.

That code snippet detects in which window the mouse click was done so i could modify a little to make it work. But the problem is that the hook using SetWindowsHookEx is not being set on a specific window, instead it listens for all mouse clicks in all windows (independently of the window) so i am interested in only set the hook in a specific window.

I have the window handle of the window in which i am interested in but now i need to know how to set the hook only in this window. How can i do this? I don't want to listen mouse events globally on all windows.

Thank you very much and sorry, i am completely new in using hooks.


Solution

  • SetWindowsHookEx() hooks are installed either globally or per-thread. It has no concept of windows.

    The code you linked to is using a WH_MOUSE_LL hook, which can be used only globally not per-thread, and as such its callback does not give you any information about which window receives each mouse event. It does, however, give you the screen coordinates of each mouse event. You can determine the current HWND located at those coordinates by using WindowFromPoint() and ChildWindowFromPoint/Ex().

    On the other hand, an WH_MOUSE hook can be installed per-thread. You can get the thread ID of a given HWND by using GetWindowThreadProcessId(). This way, the hook callback will give you mouse events only for windows owned by that thread, and will also give you the HWND that receives each event, so you can ignore events for windows you are not interested in.

    Note: if the HWND you are interested in monitoring belongs to another process than the one that is installing the hook, you will have to implement your hook callback in a DLL. Doing that is not required when using a WH_MOUSE_LL hook, or when hooking a specific thread that is owned by the same process that is installing the hook.