SetWindowsHookEx in C#

SetWindowsHookEx specifies the last two parameters thusly:

  • hMod

[in] Handle to the DLL containing the
hook procedure pointed to by the lpfn
parameter. The hMod parameter must be
set to NULL if the dwThreadId
parameter specifies a thread created
by the current process and if the hook
procedure is within the code
associated with the current process.

  • dwThreadId

[in] Specifies the identifier of the
thread with which the hook procedure
is to be associated. If this parameter
is zero, the hook procedure is
associated with all existing threads
running in the same desktop as the
calling thread.

I’m not sure you can use a .NET dll in the manner required, but you can certainly try.

Grab hMod via Marshal.GetHINSTANCE(typeof(Form1).Module) and dwThreadId via Process.Threads. Alternatively, set dwThreadId to 0 if you want a global hook (ie. a hook for all GetMessage() calls in the current desktop) but beware of the performance penalties.

Leave a Comment