Reading through George Mamaladze c# "global mouse key hook" source code I am trying to figure how some code works. Here is the "corazon" generally
public delegate IntPtr HookProcedure(int nCode, IntPtr wParam, IntPtr lParam);
private static Handle HookGlobal(int hookId, Callback callback)
{
HookProcedure hookProc = (code, param, lParam) => MyProc(code, param, lParam, callback);
Handle handle = SetWindowsHookEx(
hookId,
hookProc,
Process.GetCurrentProcess().MainModule.BaseAddress,
0);
return handle;
}
private static IntPtr MyProc(int nCode, IntPtr wParam, IntPtr lParam, Callback callback)
{
var callbackData = new CallbackData(wParam, lParam);
bool continueProcessing = callback(callbackData);
if (!continueProcessing)
{ return new IntPtr(-1); }
return CallNextHookEx(IntPtr.Zero, nCode, wParam, lParam);
}
The message pump set by WinApi function SetWindowsHookEx will call the MyProc method with message data.
HHOOK WINAPI SetWindowsHookEx(
_In_ int idHook,
_In_ HOOKPROC lpfn,
_In_ HINSTANCE hMod,
_In_ DWORD dwThreadId
);
According to MSDN, the HOOKPROC type defines a pointer to the callback function. (example...) MouseProc is a placeholder for the application-defined or library-defined function name. (There are several placeholder procedure callbacks...)
LRESULT CALLBACK MouseProc(
_In_ int code,
WPARAM wParam,
_In_ LPARAM lParam
);
Does the hookProc delegate instance keep reference to the lambda and thus to MyProc method in George's code?
Here is a simpler approach from Stephen Taub's MSDN blog
private delegate IntPtr HookProcedure(int nCode, IntPtr wParam, IntPtr lParam);
private static HookProcedure procedure = Callback;
private static IntPtr _hookID = IntPtr.Zero;
public static void SetHook()
{
_hookID = SetWindowsHookEx(
WH_KEYBOARD_LL,
procedure,
Process.GetCurrentProcess().MainModule,
0);
}
private static IntPtr Callback(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode >= 0)
{
}
return CallNextHookEx(_hookId, nCode, wParam, lParam);
}
They should achieve the same thing. What's George up to with this warped stuff? An explanation may help with my dizziness or shortness of breath.