I have develop a application that use a global keybord/mouse hook. It works perfect in Windows 7, but not in Windows XP.
When I call SetWindowsHookEx in Windows XP, I get error code 1428
int MouseLowLevel = 14
int code = SetWindowsHookEx(MouseLowLevel,
MouseHookProc,
IntPtr.Zero,
0);
private IntPtr MouseHookProc(int nCode, IntPtr wParam, IntPtr lParam) {}
Curious that this code doesn't fail on Win7 but I certainly never tried. But it is correct behavior, looks like they improved it. The argument validation for SetWindowsHookEx() requires a valid non-zero 3rd or 4th argument. The error code is highly descriptive, from WinError.h:
//
// MessageId: ERROR_HOOK_NEEDS_HMOD
//
// MessageText:
//
// Cannot set nonlocal hook without a module handle.
//
#define ERROR_HOOK_NEEDS_HMOD 1428L
Any module handle will do since it doesn't actually get used for low-level hooks, no DLL needs to be injected to make them work. Some care in selecting one is required for .NET 4 since its CLR no longer fakes module handles for pure managed assemblies. A good one to use is the one you get out of pinvoking LoadLibrary("user32.dll") since it is always already loaded. You don't have to call FreeLibrary().
You'll need this declaration to call LoadLibrary:
[DllImport("kernel32", SetLastError=true, CharSet = CharSet.Auto)]
private static extern IntPtr LoadLibrary(string fileName);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With