问题
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) {}
回答1:
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);
来源:https://stackoverflow.com/questions/10516448/error-when-using-setwindowshookex-in-windows-xp-but-not-in-windows-7